repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jbwyme/action-destinations
packages/destination-actions/src/destinations/slack/postToChannel/index.ts
import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Post Message', description: 'Post a message to a Slack channel.', fields: { url: { label: 'Webhook URL', description: 'Slack webhook URL.', type: 'string', required: true, format: 'uri' }, text: { label: 'Message', required: true, description: "The text message to post to Slack. You can use [Slack's formatting syntax.](https://api.slack.com/reference/surfaces/formatting)", type: 'text' }, channel: { label: 'Channel', description: 'Slack channel to post message to.', type: 'string' }, username: { label: 'User', description: 'User name to post messages as.', type: 'string', default: 'Segment' }, icon_url: { label: 'Icon URL', description: 'URL for user icon image.', type: 'string', default: 'https://logo.clearbit.com/segment.com' } }, perform: (request, { payload }) => { return request(payload.url, { method: 'post', json: { channel: payload.channel, text: payload.text, username: payload.username, icon_url: payload.icon_url } }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/__tests__/viewCart.test.ts
<filename>packages/destination-actions/src/destinations/google-analytics-4/__tests__/viewCart.test.ts import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import ga4 from '../index' const testDestination = createTestIntegration(ga4) const apiSecret = '<KEY>' const measurementId = 'G-TESTTOKEN' describe('GA4', () => { describe('View Cart', () => { it('should handle basic mapping overrides', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Cart Viewed', userId: 'abc123', anonymousId: 'anon-2134', type: 'track', properties: { products: [ { product_id: '12345abcde', name: 'Quadruple Stack Oreos, 52 ct', currency: 'USD', price: 12.99, quantity: 1 } ] } }) const responses = await testDestination.testAction('viewCart', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.anonymousId' }, items: [ { item_name: { '@path': `$.properties.products.0.name` }, item_id: { '@path': `$.properties.products.0.product_id` }, currency: { '@path': `$.properties.products.0.currency` }, price: { '@path': `$.properties.products.0.price` }, quantity: { '@path': `$.properties.products.0.quantity` } } ] }, useDefaultMappings: false }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(201) expect(responses[0].request.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "content-type": Array [ "application/json", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.body).toMatchInlineSnapshot( `"{\\"client_id\\":\\"anon-2134\\",\\"events\\":[{\\"name\\":\\"view_cart\\",\\"params\\":{\\"items\\":[{\\"item_name\\":\\"Quadruple Stack Oreos, 52 ct\\",\\"item_id\\":\\"12345abcde\\",\\"currency\\":\\"USD\\",\\"price\\":12.99,\\"quantity\\":1}]}}]}"` ) }) it('should throw an error when no items array is included', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Cart Viewed', userId: '1234abc', type: 'track', properties: { currency: 'USD', price: 10 } }) try { await testDestination.testAction('viewCart', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.userId' }, currency: { '@path': '$.properties.currency' }, value: { '@path': '$.properties.price' } }, useDefaultMappings: false }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe("The root value is missing the required field 'items'.") } }) it('should throw an error when a value is included with no currency', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Cart Viewed', userId: 'abc123', type: 'track', properties: { value: 42, products: [ { product_id: '12345', name: 'Monopoly: 3rd Edition', currency: 'USD' } ] } }) try { await testDestination.testAction('viewCart', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.userId' }, value: { '@path': '$.properties.value' }, items: [ { item_id: { '@path': '$.properties.product_id' }, item_name: { '@path': '$.properties.name' }, currency: { '@path': '$.properties.currency' } } ] }, useDefaultMappings: true }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe('Currency is required if value is set.') } }) it('should throw an error when no currency is included', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Cart Viewed', userId: 'abc123', type: 'track', properties: { products: [ { product_id: '123456' } ] } }) try { await testDestination.testAction('viewCart', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.userId' }, items: [ { item_id: { '@path': '$.properties.products.0.product_id' } } ] }, useDefaultMappings: false }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe('One of item-level currency or top-level currency is required.') } }) }) })
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/triggerCampaign/index.ts
<gh_stars>0 import type { ActionDefinition, DynamicFieldResponse, RequestFn } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' interface Campaigns { campaigns: Campaign[] } interface Campaign { id: string name: string } const idAutocomplete: RequestFn<Settings, Payload, DynamicFieldResponse> = async (request, { settings }) => { const response = await request<Campaigns>('https://beta-api.customer.io/v1/api/campaigns', { username: settings.siteId, password: settings.apiKey }) const items = response.data.campaigns.map((campaign) => ({ label: campaign.name, value: campaign.id })) return { body: { data: items, pagination: {} } } } const action: ActionDefinition<Settings, Payload> = { title: 'Trigger Broadcast Campaign', description: 'Trigger a Customer.io broadcast campaign.', // Hide so we can delete later. No customers currently using it. hidden: true, fields: { id: { label: 'Campaign ID', description: 'ID of the campaign to trigger.', type: 'number', required: true, dynamic: true }, data: { label: 'Data', description: 'Custom Liquid merge data to include with the trigger.', type: 'object', default: { '@path': '$.properties' } }, recipients: { label: 'Recipients', description: 'Additional recipient conditions to filter recipients. If this is used, "IDs" may not be used.', type: 'object' }, ids: { label: 'Profile IDs', description: 'List of profile IDs to use as campaign recipients. If this is used, "Recipients" may not be used.', type: 'string', multiple: true } }, dynamicFields: { id: idAutocomplete }, perform: (request, { payload }) => { return request(`https://api.customer.io/v1/api/campaigns/${payload.id}/triggers`, { method: 'post', json: { ids: payload.ids, data: payload.data, recipients: payload.recipients } }) } } export default action
jbwyme/action-destinations
packages/cli/templates/destinations/custom-auth/index.ts
<filename>packages/cli/templates/destinations/custom-auth/index.ts import type { DestinationDefinition } from '@segment/actions-core' import type { Settings } from './generated-types' const destination: DestinationDefinition<Settings> = { name: '{{name}}', slug: '{{slug}}', mode: 'cloud', authentication: { scheme: 'custom', fields: {}, testAuthentication: (request) => { // Return a request that tests/validates the user's credentials. // If you do not have a way to validate the authentication fields safely, // you can remove the `testAuthentication` function, though discouraged. } }, actions: {} } export default destination
jbwyme/action-destinations
packages/cli/templates/destinations/browser/__tests__/index.test.ts
<filename>packages/cli/templates/destinations/browser/__tests__/index.test.ts import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import plugins, { destination } from '../index' describe('{{name}}', () => {})
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/customEvent/index.ts
<filename>packages/destination-actions/src/destinations/google-analytics-4/customEvent/index.ts<gh_stars>0 import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Send a Custom Event', description: 'Send events to a custom event in GA4', defaultSubscription: 'type = "track"', fields: { clientId: { label: 'Client ID', description: 'Uniquely identifies a user instance of a web client.', type: 'string', required: true, default: { '@if': { exists: { '@path': '$.userId' }, then: { '@path': '$.userId' }, else: { '@path': '$.anonymousId' } } } }, name: { label: 'Event Name', description: 'The unique name of the custom event created in GA4.', type: 'string', required: true }, params: { label: 'Event Parameters', description: 'The event parameters to send to Google', type: 'object', default: { '@path': '$.properties' } } }, perform: (request, { payload }) => { return request('https://www.google-analytics.com/mp/collect', { method: 'POST', json: { client_id: payload.clientId, events: [ { name: payload.name, params: payload.params } ] } }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/createUpdatePerson/generated-types.ts
<filename>packages/destination-actions/src/destinations/customerio/createUpdatePerson/generated-types.ts // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * ID used to uniquely identify person in Customer.io. */ id: string /** * Anonymous ID to uniquely identify person in Customer.io. */ anonymous_id?: string /** * Person's email address. */ email: string /** * Timestamp for when the person was created. Default is current date and time. */ created_at?: string /** * Optional custom attributes for this person. When updating a person, attributes are added and not removed. */ custom_attributes?: { [k: string]: unknown } }
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-enhanced-conversions/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * Tracking id that uniquely identifies your advertiser account. */ conversionTrackingId: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/__tests__/trackEvent.test.ts
<gh_stars>0 import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import CustomerIO from '../index' const testDestination = createTestIntegration(CustomerIO) const trackEventService = nock('https://track.customer.io/api/v1') describe('CustomerIO', () => { describe('trackEvent', () => { it('should work with default mappings when a userId is supplied', async () => { const userId = 'abc123' const name = 'testEvent' const type = 'track' const data = { property1: 'this is a test' } trackEventService.post(`/customers/${userId}/events`).reply(200, {}) const event = createTestEvent({ event: name, type, userId, properties: data }) const responses = await testDestination.testAction('trackEvent', { event, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(200) expect(responses[0].data).toMatchObject({}) expect(responses[0].options.json).toMatchObject({ name, type, data }) }) it('should work with default mappings when a anonymousId is supplied', async () => { const anonymousId = 'anonymous123' const name = 'test event' const type = 'track' const data = { property1: 'this is a test' } trackEventService.post(`/events`).reply(200, {}) const event = createTestEvent({ event: name, type, anonymousId, properties: data, userId: undefined }) const responses = await testDestination.testAction('trackEvent', { event, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(200) expect(responses[0].data).toMatchObject({}) expect(responses[0].options.json).toMatchObject({ name, type, data, anonymous_id: anonymousId }) }) it('should error when the name field is not supplied', async () => { const type = 'track' const data = { property1: 'this is a test' } trackEventService.post(`/events`).reply(200, {}) const event = createTestEvent({ event: undefined, type, properties: data, anonymousId: undefined, userId: undefined }) try { await testDestination.testAction('trackEvent', { event, useDefaultMappings: true }) fail('This test should have thrown an error') } catch (e) { expect(e.message).toBe("The root value is missing the required field 'name'.") } }) }) })
jbwyme/action-destinations
packages/cli/src/commands/push.ts
<gh_stars>0 import { Command, flags } from '@oclif/command' import type { DestinationDefinition as CloudDestinationDefinition, MinimalInputField } from '@segment/actions-core' import { fieldsToJsonSchema } from '@segment/actions-core' import { manifest as cloudManifest, ManifestEntry as CloudManifest } from '@segment/action-destinations' import { manifest as browserManifest, ManifestEntry as BrowserManifest, BrowserDestinationDefinition } from '@segment/browser-destinations' import chalk from 'chalk' import { uniq, pick, omit, sortBy, mergeWith } from 'lodash' import { diffString } from 'json-diff' import ora from 'ora' import type { ClientRequestError, DestinationMetadata, DestinationMetadataActionCreateInput, DestinationMetadataActionFieldCreateInput, DestinationMetadataActionsUpdateInput, DestinationMetadataOption, DestinationMetadataOptions, DestinationSubscriptionPresetFields, DestinationSubscriptionPresetInput } from '../lib/control-plane-service' import { prompt } from '../lib/prompt' import { OAUTH_OPTIONS, RESERVED_FIELD_NAMES } from '../constants' import { getDestinationMetadatas, getDestinationMetadataActions, updateDestinationMetadata, updateDestinationMetadataActions, createDestinationMetadataActions, setSubscriptionPresets } from '../lib/control-plane-client' import { DestinationDefinition, hasOauthAuthentication } from '../lib/destinations' import type { JSONSchema4 } from 'json-schema' type BaseActionInput = Omit<DestinationMetadataActionCreateInput, 'metadataId'> // Right now it's possible for browser destinations and cloud destinations to have the same // metadataId. This is because we currently rely on a separate directory for all web actions. // So here we need to intelligently merge them until we explore colocating all actions with a single // definition file. const manifest: Record<string, CloudManifest | BrowserManifest> = mergeWith( {}, cloudManifest, browserManifest, (objValue, srcValue) => { if (Object.keys(objValue?.definition?.actions ?? {}).length === 0) { return } for (const [actionKey, action] of Object.entries(srcValue.definition?.actions ?? {})) { if (actionKey in objValue.definition.actions) { throw new Error( `Could not merge browser + cloud actions because there is already an action with the same key "${actionKey}"` ) } objValue.definition.actions[actionKey] = action } return objValue } ) export default class Push extends Command { private spinner: ora.Ora = ora() static description = `Introspects your integration definition to build and upload your integration to Segment. Requires \`robo stage.ssh\` or \`robo prod.ssh\`.` static examples = [`$ ./bin/run push`] static flags = { help: flags.help({ char: 'h' }), force: flags.boolean({ char: 'f' }) } static args = [] async run() { const { flags } = this.parse(Push) const { metadataIds } = await prompt<{ metadataIds: string[] }>({ type: 'multiselect', name: 'metadataIds', message: 'Pick the definitions you would like to push to Segment:', choices: sortBy(Object.entries(manifest), '[1].definition.name').map(([metadataId, entry]) => ({ title: entry.definition.name, value: metadataId })) }) if (!metadataIds.length) { this.warn(`You must select at least one destination. Exiting.`) this.exit() } this.spinner.start( `Fetching existing definitions for ${metadataIds .map((id) => chalk.greenBright(manifest[id].definition.name)) .join(', ')}...` ) const [metadatas, actions] = await Promise.all([ getDestinationMetadatas(metadataIds), getDestinationMetadataActions(metadataIds) ]) if (metadatas.length !== Object.keys(metadataIds).length) { this.spinner.fail() throw new Error('Number of metadatas must match number of schemas') } this.spinner.stop() for (const metadata of metadatas) { const entry = manifest[metadata.id] const definition = entry.definition const slug = metadata.slug this.log('') this.log(`${chalk.bold.whiteBright(slug)}`) this.spinner.start(`Generating diff for ${chalk.bold(slug)}...`) const actionsToUpdate: DestinationMetadataActionsUpdateInput[] = [] const actionsToCreate: DestinationMetadataActionCreateInput[] = [] const existingActions = actions.filter((a) => a.metadataId === metadata.id) for (const [actionKey, action] of Object.entries(definition.actions)) { const platform = action.platform ?? 'cloud' // Note: this implies that changing the slug is a breaking change const existingAction = existingActions.find((a) => a.slug === actionKey && a.platform === platform) const fields: DestinationMetadataActionFieldCreateInput[] = Object.keys(action.fields).map((fieldKey) => { const field = action.fields[fieldKey] if (action.platform === 'web' && field.dynamic) { this.error( `The field key "${fieldKey}" is configured to be a "dynamic" field. Web actions do not support dynamic fields.` ) } return { fieldKey, type: field.type, label: field.label, description: field.description, defaultValue: field.default, required: field.required ?? false, multiple: field.multiple ?? false, // TODO implement choices: null, dynamic: field.dynamic ?? false, placeholder: field.placeholder ?? '', allowNull: field.allowNull ?? false, fieldSchema: getFieldPropertySchema(fieldKey, field) } }) const base: BaseActionInput = { slug: actionKey, name: action.title ?? 'Unnamed Action', description: action.description ?? '', platform, hidden: action.hidden ?? false, defaultTrigger: action.defaultSubscription ?? null, fields } if (existingAction) { actionsToUpdate.push({ ...base, actionId: existingAction.id }) } else { actionsToCreate.push({ ...base, metadataId: metadata.id }) } } const hasBrowserActions = Object.values(definition.actions).some((action) => action.platform === 'web') const hasCloudActions = Object.values(definition.actions).some( (action) => !action.platform || action.platform === 'cloud' ) const platforms = { browser: hasBrowserActions || hasCloudActions, server: hasCloudActions, mobile: false } const options = getOptions(metadata, definition) const basicOptions = getBasicOptions(metadata, options) const diff = diffString( asJson({ basicOptions: filterOAuth(metadata.basicOptions), options: pick(metadata.options, filterOAuth(Object.keys(options))), platforms: metadata.platforms, actions: sortBy( existingActions.map((action) => ({ ...omit(action, ['id', 'metadataId', 'createdAt', 'updatedAt']), fields: action.fields?.map((field) => omit(field, ['id', 'metadataActionId', 'sortOrder', 'createdAt', 'updatedAt']) ) })), ['name'] ) }), asJson({ basicOptions: filterOAuth(basicOptions), options: pick(options, filterOAuth(Object.keys(options))), platforms, // eslint-disable-next-line @typescript-eslint/no-explicit-any actions: sortBy( ([] as Array<DestinationMetadataActionCreateInput | DestinationMetadataActionsUpdateInput>) .concat(actionsToUpdate, actionsToCreate) .map((action) => ({ ...omit(action, ['id', 'actionId', 'metadataId']), fields: action.fields?.map((field) => omit(field, ['id', 'metadataActionId', 'sortOrder', 'createdAt', 'updatedAt']) ) })), ['name'] ) }) ) if (diff) { this.spinner.warn(`Detected changes for ${chalk.bold(slug)}, please review:`) this.log(`\n${diff}`) } else if (flags.force) { const newDefinition = definitionToJson(definition) this.spinner.warn(`No change detected for ${chalk.bold(slug)}. Using force, please review:`) this.log(`\n${JSON.stringify(newDefinition, null, 2)}`) } else { this.spinner.info(`No change for ${chalk.bold(slug)}. Skipping.`) continue } const { shouldContinue } = await prompt({ type: 'confirm', name: 'shouldContinue', message: `Publish change for ${slug}?`, initial: false }) if (!shouldContinue) { continue } try { await Promise.all([ updateDestinationMetadata(metadata.id, { basicOptions, options, platforms }), updateDestinationMetadataActions(actionsToUpdate), createDestinationMetadataActions(actionsToCreate) ]) } catch (e) { const error = e as ClientRequestError chalk.red(error.message) if (error.isMultiError) { error.errors.map((error) => error.message).forEach((error) => chalk.red(error)) } } const allActions = await getDestinationMetadataActions([metadata.id]) const presets: DestinationSubscriptionPresetInput[] = [] for (const preset of definition.presets ?? []) { const associatedAction = allActions.find((a) => a.slug === preset.partnerAction) if (!associatedAction) continue presets.push({ actionId: associatedAction.id, name: preset.name ?? associatedAction.name, trigger: preset.subscribe, fields: (preset.mapping as DestinationSubscriptionPresetFields) ?? {} }) } // We have to wait to do this until after the associated actions are created (otherwise it may fail) await setSubscriptionPresets(metadata.id, presets) } } } function getFieldPropertySchema(fieldKey: string, field: MinimalInputField): JSONSchema4 { // Build a temporary object in which they key = field name and value = field properties // since that's the structure expected by fieldsToJsonSchema const tmpFieldObject: Record<string, MinimalInputField> = {} tmpFieldObject[fieldKey] = field return fieldsToJsonSchema(tmpFieldObject) } function filterOAuth(optionList: string[]) { return optionList.filter((item) => item !== 'oauth') } function asJson(obj: unknown) { return JSON.parse(JSON.stringify(obj)) } function definitionToJson(definition: DestinationDefinition) { // Create a copy that only includes serializable properties const copy = JSON.parse(JSON.stringify(definition)) for (const action of Object.keys(copy.actions)) { delete copy.actions[action].dynamicFields copy.actions[action].hidden = copy.actions[action].hidden ?? false } return copy } function getBasicOptions(metadata: DestinationMetadata, options: DestinationMetadataOptions): string[] { return uniq([...metadata.basicOptions, ...Object.keys(options)]) } // Note: exporting for testing purposes only export function getOptions( metadata: DestinationMetadata, definition: DestinationDefinition ): DestinationMetadataOptions { const options: DestinationMetadataOptions = { ...metadata.options } const publicSettings = (definition as BrowserDestinationDefinition).settings const authFields = (definition as CloudDestinationDefinition).authentication?.fields const settings = { ...publicSettings, ...authFields } for (const [fieldKey, schema] of Object.entries(settings)) { const validators: string[][] = [] if (RESERVED_FIELD_NAMES.includes(fieldKey.toLowerCase()) && hasOauthAuthentication(definition)) { throw new Error(`Schema contains a field definition that uses a reserved name: ${fieldKey}`) } if (schema.required) { validators.push(['required', `The ${fieldKey} property is required.`]) } // Everything in `authentication.fields` should be private. Otherwise, public is fine const isPrivateSetting = typeof authFields === 'object' && fieldKey in authFields let type: DestinationMetadataOption['type'] = schema.type if (Array.isArray(schema.choices)) { type = 'select' } if (schema.multiple) { if (type !== 'string') { throw new Error("`multiple: true` can only be used with `type: 'string'`.") } // Use array type for any `multiple` fields type = 'array' } // Validate that select choices match the specified field type. if (type === 'select') { const allChoicesMatchType = schema.choices?.every((choice) => typeof choice.value === schema.type) if (!allChoicesMatchType) { throw new Error(`All choices must have a value that matches the 'type' for this field.`) } } options[fieldKey] = { default: schema.default ?? '', description: schema.description, encrypt: schema.type === 'password', hidden: false, label: schema.label, private: isPrivateSetting, scope: 'event_destination', type, options: schema.choices?.map((choice) => ({ value: choice.value, label: choice.label, text: choice.label })), validators } } // Add oauth settings if (hasOauthAuthentication(definition)) { options['oauth'] = OAUTH_OPTIONS } return options }
jbwyme/action-destinations
packages/destination-actions/src/destinations/pipedrive/createUpdateOrganization/index.ts
<gh_stars>0 import dayjs from '../../../lib/dayjs' import { get } from '@segment/actions-core' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Create or Update Organization', description: "Update an organization in Pipedrive or create it if it doesn't exist yet.", defaultSubscription: 'type = "group"', fields: { identifier: { label: 'Organization ID', description: 'Identifier used to find existing organization in Pipedrive. Typically this is the name but it can also be a custom field value. Custom organization fields may be included by using the long hash keys of the custom fields. These look like "33595c732cd7a027c458ea115a48a7f8a254fa86".', type: 'string', required: true }, name: { label: 'Organization Name', description: 'Name of the organization', type: 'string', required: true }, owner_id: { label: 'Owner ID', description: 'ID of the user who will be marked as the owner of this organization. Default is the user who ownes the API token.', type: 'number' }, add_time: { label: 'Created At', description: 'If the organization is created, use this timestamp as the creation timestamp. Format: YYY-MM-DD HH:MM:SS', type: 'string' } }, perform: async (request, { payload, settings }) => { const search = await request(`https://${settings.domain}.pipedrive.com/api/v1/organizations/search`, { searchParams: { term: payload.identifier } }) const organizationId = get(search.data, 'data.items[0].item.id') const organization = { name: payload.name, owner_id: payload.owner_id } if (organizationId === undefined || organizationId === null) { return request(`https://${settings.domain}.pipedrive.com/api/v1/organizations`, { method: 'post', json: { ...organization, add_time: payload.add_time ? dayjs.utc(payload.add_time).format('YYYY-MM-DD HH:MM:SS') : undefined } }) } return request(`https://${settings.domain}.pipedrive.com/api/v1/organizations/${organizationId}`, { method: 'put', json: organization }) } } export default action
jbwyme/action-destinations
packages/core/src/mapping-kit/index.ts
<gh_stars>0 import { get } from '../get' import { JSONObject, JSONValue, JSONLike, JSONLikeObject } from '../json-object' import { isDirective } from './is-directive' import { render } from './placeholders' import { realTypeOf, isObject, isArray } from '../real-type-of' import { removeUndefined } from '../remove-undefined' import validate from './validate' type Directive = (options: JSONValue, payload: JSONObject) => JSONLike type StringDirective = (value: string, payload: JSONObject) => JSONLike interface Directives { [directive: string]: Directive | undefined } const directives: Directives = {} const directiveRegExp = /^@[a-z][a-zA-Z0-9]+$/ function registerDirective(name: string, fn: Directive): void { if (!directiveRegExp.exec(name)) { throw new Error(`"${name}" is an invalid directive name`) } directives[name] = fn } function registerStringDirective(name: string, fn: StringDirective): void { registerDirective(name, (value, payload) => { const str = resolve(value, payload) if (typeof str !== 'string') { throw new Error(`${name}: expected string, got ${realTypeOf(str)}`) } return fn(str, payload) }) } function runDirective(obj: JSONObject, payload: JSONObject): JSONLike { const name = Object.keys(obj).find((key) => key.startsWith('@')) as string const directiveFn = directives[name] const value = obj[name] if (typeof directiveFn !== 'function') { throw new Error(`${name} is not a valid directive, got ${realTypeOf(directiveFn)}`) } return directiveFn(value, payload) } registerDirective('@if', (opts, payload) => { let condition = false if (!isObject(opts)) { throw new Error('@if requires an object with an "exists" key') } if (opts.exists !== undefined) { const value = resolve(opts.exists, payload) condition = value !== undefined && value !== null } else { throw new Error('@if requires an "exists" key') } if (condition && opts.then !== undefined) { return resolve(opts.then, payload) } else if (!condition && opts.else) { return resolve(opts.else, payload) } }) registerStringDirective('@path', (path, payload) => { return get(payload, path.replace('$.', '')) }) registerStringDirective('@template', (template: string, payload) => { return render(template, payload) }) // Literal should be used in place of 'empty' template strings as they will not resolve correctly registerDirective('@literal', (value, payload) => { return resolve(value, payload) }) /** * Resolves a mapping value/object by applying the input payload based on directives * *WARNING* This function mutates `mapping` when an object * @param mapping - the mapping directives or raw values to resolve * @param payload - the input data to apply to the mapping directives * @todo support arrays or array directives? */ function resolve(mapping: JSONLike, payload: JSONObject): JSONLike { if (!isObject(mapping) && !isArray(mapping)) { return mapping } if (isDirective(mapping)) { return runDirective(mapping, payload) } if (Array.isArray(mapping)) { return mapping.map((value) => resolve(value, payload)) } for (const key of Object.keys(mapping)) { const value = mapping[key] mapping[key] = resolve(value, payload) } return mapping } /** * Validates and transforms a mapping by applying the input payload * based on the directives and raw values defined in the mapping object * @param mapping - the directives and raw values * @param data - the input data to apply to directives */ export function transform(mapping: JSONLikeObject, data: unknown = {}): JSONObject { const realType = realTypeOf(data) if (realType !== 'object') { throw new Error(`payload must be an object, got ${realType}`) } // throws if the mapping config is invalid validate(mapping) const cloned = cloneJson(mapping) const resolved = resolve(cloned, data as JSONObject) const cleaned = removeUndefined(resolved) // Cast because we know there are no `undefined` values anymore return cleaned as JSONObject } function cloneJson<T>(obj: T): T { return JSON.parse(JSON.stringify(obj)) }
jbwyme/action-destinations
packages/cli/templates/destinations/basic-auth/index.ts
import type { DestinationDefinition } from '@segment/actions-core' import type { Settings } from './generated-types' const destination: DestinationDefinition<Settings> = { name: '{{name}}', slug: '{{slug}}', mode: 'cloud', authentication: { scheme: 'basic', fields: { username: { label: 'Username', description: 'Your {{name}} username', type: 'string', required: true }, password: { label: 'password', description: 'Your {{name}} password.', type: 'string', required: true } }, testAuthentication: (request) => { // Return a request that tests/validates the user's credentials. // If you do not have a way to validate the authentication fields safely, // you can remove the `testAuthentication` function, though discouraged. } }, extendRequest({ settings }) { return { username: settings.username, password: <PASSWORD> } }, actions: {} } export default destination
jbwyme/action-destinations
packages/destination-actions/src/destinations/pipedrive/createUpdatePerson/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * Identifier used to find existing person in Pipedrive. Can be an email, name, phone number, or custom field value. Custom person fields may be included by using the long hash keys of the custom fields. These look like "33595c732cd7a027c458ea115a48a7f8a254fa86". */ identifier: string /** * Name of the person */ name: string /** * ID of the organization this person will belong to. */ org_id?: number /** * Email addresses for this person. */ email?: string[] /** * Phone number for the person. */ phone?: string /** * If the person is created, use this timestamp as the creation timestamp. Format: YYY-MM-DD HH:MM:SS */ add_time?: string }
jbwyme/action-destinations
packages/core/src/destination-kit/action.ts
import { EventEmitter } from 'events' import createRequestClient from '../create-request-client' import { JSONLikeObject, JSONObject } from '../json-object' import { transform } from '../mapping-kit' import { fieldsToJsonSchema } from './fields-to-jsonschema' import { Response } from '../fetch' import type { ModifiedResponse } from '../types' import type { DynamicFieldResponse, InputField, RequestExtension, ExecuteInput, Result } from './types' import type { NormalizedOptions } from '../request-client' import type { JSONSchema4 } from 'json-schema' import { validateSchema } from '../schema-validation' import { AuthTokens } from './parse-settings' type MaybePromise<T> = T | Promise<T> type RequestClient = ReturnType<typeof createRequestClient> // eslint-disable-next-line @typescript-eslint/no-explicit-any export type RequestFn<Settings, Payload, Return = any> = ( request: RequestClient, data: ExecuteInput<Settings, Payload> ) => MaybePromise<Return> // eslint-disable-next-line @typescript-eslint/no-explicit-any export interface BaseActionDefinition { /** The display title of the action */ title: string /** The display description of the action */ description: string /** * The target platform for the action * @default 'cloud' */ platform?: 'cloud' | 'web' /** An optional fql query that will be used to prepopulate the action when it is first set up */ defaultSubscription?: string /** Whether or not this action should be visible/configurable in the UI */ hidden?: boolean /** * The fields used to perform the action. These fields should match what the partner API expects. */ fields: Record<string, InputField> } // eslint-disable-next-line @typescript-eslint/no-explicit-any export interface ActionDefinition<Settings, Payload = any> extends BaseActionDefinition { /** * A way to "register" dynamic fields. * This is likely going to change as we productionalize the data model and definition object */ dynamicFields?: { [K in keyof Payload]?: RequestFn<Settings, Payload, DynamicFieldResponse> } /** The operation to perform when this action is triggered */ perform: RequestFn<Settings, Payload> } interface ExecuteDynamicFieldInput<Settings, Payload> { settings: Settings payload: Payload page?: string } /** * Action is the beginning step for all partner actions. Entrypoints always start with the * MapAndValidateInput step. */ export class Action<Settings, Payload extends JSONLikeObject> extends EventEmitter { readonly definition: ActionDefinition<Settings, Payload> readonly destinationName: string readonly schema?: JSONSchema4 private extendRequest: RequestExtension<Settings, Payload> | undefined constructor( destinationName: string, definition: ActionDefinition<Settings, Payload>, extendRequest?: RequestExtension<Settings, Payload> ) { super() this.definition = definition this.destinationName = destinationName this.extendRequest = extendRequest // Generate json schema based on the field definitions if (Object.keys(definition.fields ?? {}).length) { this.schema = fieldsToJsonSchema(definition.fields) } } async execute(bundle: { data: unknown settings: Settings mapping: JSONObject auth: AuthTokens | undefined }): Promise<Result[]> { // TODO cleanup results... not sure it's even used const results: Result[] = [] // Resolve/transform the mapping with the input data const payload = transform(bundle.mapping, bundle.data) as Payload results.push({ output: 'Mappings resolved' }) // Validate the resolved payload against the schema if (this.schema) { validateSchema(payload, this.schema, `${this.destinationName}:${this.definition.title}`) results.push({ output: 'Payload validated' }) } // Construct the data bundle to send to an action const dataBundle = { rawData: bundle.data, rawMapping: bundle.mapping, settings: bundle.settings, payload, auth: bundle.auth } // Construct the request client and perform the action const output = await this.performRequest(this.definition.perform, dataBundle) results.push({ output: output as JSONObject }) return results } executeDynamicField(field: string, data: ExecuteDynamicFieldInput<Settings, Payload>): unknown { const fn = this.definition.dynamicFields?.[field] if (typeof fn !== 'function') { return { data: [], pagination: {} } } return this.performRequest(fn, data) } /** * Perform a request using the definition's request client * the given request function * and given data bundle */ private async performRequest( requestFn: RequestFn<Settings, Payload>, data: ExecuteInput<Settings, Payload> ): Promise<unknown> { const requestClient = this.createRequestClient(data) const response = await requestFn(requestClient, data) return this.parseResponse(response) } private createRequestClient(data: ExecuteInput<Settings, Payload>): RequestClient { // TODO turn `extendRequest` into a beforeRequest hook const options = this.extendRequest?.(data) ?? {} return createRequestClient(options, { afterResponse: [this.afterResponse.bind(this)] }) } // Keep track of the request(s) associated with a response private afterResponse(request: Request, options: NormalizedOptions, response: Response) { // TODO figure out the types here... // eslint-disable-next-line @typescript-eslint/no-explicit-any const modifiedResponse: any = response modifiedResponse.request = request modifiedResponse.options = options this.emit('response', modifiedResponse) return modifiedResponse } private parseResponse(response: unknown): unknown { /** * Try to use the parsed response `.data` or `.content` string * @see {@link ../middleware/after-response/prepare-response.ts} */ if (response instanceof Response) { return (response as ModifiedResponse).data ?? (response as ModifiedResponse).content } // otherwise, we don't really know what this is, so return as-is return response } }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * The version of the SDK to use. Defaults to 3.3. */ sdkVersion: string /** * Found in the Braze Dashboard under Settings → Manage Settings → Apps → Web */ api_key: string /** * Your Braze SDK endpoint. [See more details](https://www.braze.com/docs/user_guide/administrative/access_braze/sdk_endpoints/) */ endpoint: string /** * Allow Braze to log activity from crawlers. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ allowCrawlerActivity?: boolean /** * To indicate that you trust the Braze dashboard users to write non-malicious Javascript click actions, set this property to true. If enableHtmlInAppMessages is true, this option will also be set to true. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ allowUserSuppliedJavascript?: boolean /** * Version to which user events sent to Braze will be associated with. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ appVersion?: string /** * Allows Braze to add the nonce to any <script> and <style> elements created by the SDK. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ contentSecurityNonce?: string /** * By default, the Braze SDK automatically detects and collects all device properties in DeviceProperties. To override this behavior, provide an array of DeviceProperties. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ devicePropertyAllowlist?: string[] /** * By default, users who have already granted web push permission will sync their push token with the Braze backend automatically on new session to ensure deliverability. To disable this behavior, set this option to false */ disablePushTokenMaintenance?: boolean /** * Braze automatically loads FontAwesome 4.7.0 from the FontAwesome CDN. To disable this behavior set this option to true. */ doNotLoadFontAwesome?: boolean /** * Set to true to enable logging by default */ enableLogging?: boolean /** * Set to true to enable the SDK Authentication feature. */ enableSdkAuthentication?: boolean /** * By default, the Braze SDK will show In-App Messages with a z-index of 1040 for the screen overlay, 1050 for the actual in-app message, and 1060 for the message's close button. Provide a value for this option to override these default z-indexes. */ inAppMessageZIndex?: number /** * By default, any SDK-generated user-visible messages will be displayed in the user's browser language. Provide a value for this option to override that behavior and force a specific language. The value for this option should be a ISO 639-1 Language Code. */ localization?: string /** * If you have your own service worker that you register and control the lifecycle of, set this option to true and the Braze SDK will not register or unregister a service worker. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ manageServiceWorkerExternally?: boolean /** * Provide a value to override the default interval between trigger actions with a value of your own. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ minimumIntervalBetweenTriggerActionsInSeconds?: number /** * By default, the Braze SDK will store small amounts of data (user ids, session ids), in cookies. Pass true for this option to disable cookie storage and rely entirely on HTML 5 localStorage to identify users and sessions. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions) */ noCookies?: boolean /** * By default, links from Card objects load in the current tab or window. Set this option to true to make links from cards open in a new tab or window. */ openCardsInNewTab?: boolean /** * By default, links from in-app message clicks load in the current tab or a new tab as specified in the dashboard on a message-by-message basis. Set this option to true to force all links from in-app message clicks open in a new tab or window. */ openInAppMessagesInNewTab?: boolean /** * By default, when an in-app message is showing, pressing the escape button or a click on the greyed-out background of the page will dismiss the message. Set this option to true to prevent this behavior and require an explicit button click to dismiss messages. */ requireExplicitInAppMessageDismissal?: boolean /** * If you support Safari push, you must specify this option with the website push ID that you provided to Apple when creating your Safari push certificate (starts with "web", e.g. "web.com.example.domain"). */ safariWebsitePushId?: string /** * By default, when registering users for web push notifications Braze will look for the required service worker file in the root directory of your web server at /service-worker.js. If you want to host your service worker at a different path on that server, provide a value for this option that is the absolute path to the file, e.g. /mycustompath/my-worker.js. VERY IMPORTANT: setting a value here limits the scope of push notifications on your site. For instance, in the above example, because the service ,worker file is located within the /mycustompath/ directory, appboy.registerAppboyPushMessages MAY ONLY BE CALLED from web pages that start with http://yoursite.com/mycustompath/. */ serviceWorkerLocation?: string /** * By default, sessions time out after 30 minutes of inactivity. Provide a value for this configuration option to override that default with a value of your own. */ sessionTimeoutInSeconds?: number }
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/createUpdatePerson/index.ts
<reponame>jbwyme/action-destinations<filename>packages/destination-actions/src/destinations/customerio/createUpdatePerson/index.ts import dayjs from '../../../lib/dayjs' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Create or Update Person', description: "Update a person in Customer.io or create them if they don't exist.", defaultSubscription: 'type = "identify"', fields: { id: { label: 'Person ID', description: 'ID used to uniquely identify person in Customer.io.', type: 'string', required: true, default: { '@path': '$.userId' } }, anonymous_id: { label: 'Anonymous ID', description: 'Anonymous ID to uniquely identify person in Customer.io.', type: 'string', default: { '@path': '$.anonymousId' } }, email: { label: 'Email Address', description: "Person's email address.", type: 'string', required: true, default: { '@template': '{{traits.userId}}' } }, created_at: { label: 'Created At', description: 'Timestamp for when the person was created. Default is current date and time.', type: 'string', default: { '@path': '$.timestamp' } }, custom_attributes: { label: 'Custom Attributes', description: 'Optional custom attributes for this person. When updating a person, attributes are added and not removed.', type: 'object', default: { '@path': '$.traits' } } }, perform: (request, { payload }) => { return request(`https://track.customer.io/api/v1/customers/${payload.id}`, { method: 'put', json: { ...payload.custom_attributes, email: payload.email, created_at: payload.created_at ? dayjs.utc(payload.created_at).format('X') : undefined, anonymous_id: payload.anonymous_id } }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-twilio/sendSms/index.ts
<filename>packages/destination-actions/src/destinations/personas-messaging-twilio/sendSms/index.ts import Mustache from 'mustache' import type { ActionDefinition, RequestOptions } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const getProfileApiEndpoint = (environment: string): string => { return `https://profiles.segment.${environment === 'production' ? 'com' : 'build'}` } type RequestFn = (url: string, options?: RequestOptions) => Promise<Response> const fetchProfileTraits = async ( request: RequestFn, settings: Settings, profileId: string ): Promise<Record<string, string>> => { const endpoint = getProfileApiEndpoint(settings.profileApiEnvironment) const response = await request( `${endpoint}/v1/spaces/${settings.spaceId}/collections/users/profiles/user_id:${profileId}/traits?limit=200`, { headers: { authorization: `Basic ${Buffer.from(settings.profileApiAccessToken + ':').toString('base64')}`, 'content-type': 'application/json' } } ) const body = await response.json() return body.traits } const fetchProfileExternalIds = async ( request: RequestFn, settings: Settings, profileId: string ): Promise<Record<string, string>> => { const endpoint = getProfileApiEndpoint(settings.profileApiEnvironment) const response = await request( `${endpoint}/v1/spaces/${settings.spaceId}/collections/users/profiles/user_id:${profileId}/external_ids?limit=25`, { headers: { authorization: `Basic ${Buffer.from(settings.profileApiAccessToken + ':').toString('base64')}`, 'content-type': 'application/json' } } ) const body = await response.json() const externalIds: Record<string, string> = {} for (const externalId of body.data) { externalIds[externalId.type] = externalId.id } return externalIds } interface Profile { user_id?: string anonymous_id?: string phone?: string traits: Record<string, string> } const action: ActionDefinition<Settings, Payload> = { title: 'Send SMS', description: 'Send SMS using Twilio', defaultSubscription: 'type = "track" and event = "Audience Entered"', fields: { userId: { label: 'User ID', description: 'User ID in Segment', type: 'string', required: true, default: { '@path': '$.userId' } }, toNumber: { label: 'To Number', description: 'Number to send SMS to when testing', type: 'string' }, fromNumber: { label: 'From Number', description: 'Which number to send SMS from', type: 'string', required: true }, body: { label: 'Message', description: 'Message to send', type: 'text', required: true } }, perform: async (request, { settings, payload }) => { const [traits, externalIds] = await Promise.all([ fetchProfileTraits(request, settings, payload.userId), fetchProfileExternalIds(request, settings, payload.userId) ]) const profile: Profile = { ...externalIds, traits } const phone = payload.toNumber || profile.phone if (!phone) { return } // TODO: GROW-259 remove this when we can extend the request // and we no longer need to call the profiles API first const token = Buffer.from(`${settings.twilioAccountId}:${settings.twilioAuthToken}`).toString('base64') return request(`https://api.twilio.com/2010-04-01/Accounts/${settings.twilioAccountId}/Messages.json`, { method: 'POST', headers: { authorization: `Basic ${token}` }, body: new URLSearchParams({ Body: Mustache.render(payload.body, { profile }), From: payload.fromNumber, To: phone }) }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-twilio/__tests__/send-sms.test.ts
<gh_stars>0 import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import Twilio from '..' const twilio = createTestIntegration(Twilio) const timestamp = new Date().toISOString() for (const environment of ['stage', 'production']) { const settings = { twilioAccountId: 'a', twilioAuthToken: 'b', profileApiEnvironment: environment, profileApiAccessToken: 'c', spaceId: 'd', sourceId: 'e' } const endpoint = `https://profiles.segment.${environment === 'production' ? 'com' : 'build'}` describe(`${environment} - send SMS`, () => { it('should abort when there is no `phone` external ID', async () => { nock(`${endpoint}/v1/spaces/d/collections/users/profiles/user_id:jane`).get('/traits?limit=200').reply(200, { traits: {} }) nock(`${endpoint}/v1/spaces/d/collections/users/profiles/user_id:jane`) .get('/external_ids?limit=25') .reply(200, { data: [ { type: 'user_id', id: 'jane' } ] }) const responses = await twilio.testAction('sendSms', { event: createTestEvent({ timestamp, event: 'Audience Entered', userId: 'jane' }), settings, mapping: { userId: { '@path': '$.userId' }, fromNumber: '+1234567890', body: 'Hello world, {{profile.user_id}}!' } }) expect(responses.length).toEqual(2) }) it('should send SMS', async () => { nock(`${endpoint}/v1/spaces/d/collections/users/profiles/user_id:jane`).get('/traits?limit=200').reply(200, { traits: {} }) nock(`${endpoint}/v1/spaces/d/collections/users/profiles/user_id:jane`) .get('/external_ids?limit=25') .reply(200, { data: [ { type: 'user_id', id: 'jane' }, { type: 'phone', id: '+1234567891' } ] }) const expectedTwilioRequest = new URLSearchParams() expectedTwilioRequest.set('Body', 'Hello world, jane!') expectedTwilioRequest.set('From', '+1234567890') expectedTwilioRequest.set('To', '+1234567891') const twilioRequest = nock('https://api.twilio.com/2010-04-01/Accounts/a') .post('/Messages.json', expectedTwilioRequest.toString()) .reply(201, {}) const responses = await twilio.testAction('sendSms', { event: createTestEvent({ timestamp, event: 'Audience Entered', userId: 'jane' }), settings, mapping: { userId: { '@path': '$.userId' }, fromNumber: '+1234567890', body: 'Hello world, {{profile.user_id}}!' } }) expect(responses.length).toEqual(3) expect(twilioRequest.isDone()).toEqual(true) }) }) }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/__tests__/debounce.test.ts
import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import brazeDestination from '../index' let ajs: Analytics describe('debounce', () => { beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://segment.com' }) const windowSpy = jest.spyOn(global, 'window', 'get') const documentSpy = jest.spyOn(global, 'document', 'get') windowSpy.mockImplementation(() => { return jsd.window as unknown as Window & typeof globalThis }) documentSpy.mockImplementation(() => jsd.window.document as unknown as Document) global.document.domain = 'segment.com' jest.spyOn(console, 'error').mockImplementation(() => {}) ajs = new Analytics({ writeKey: 'w_123' }) }) test('changes the integration object', async () => { const [debounce] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions: [ { partnerAction: 'debounce', name: 'Debounce', enabled: true, subscribe: 'type = "identify"', mapping: {} } ] }) await debounce.load(Context.system(), ajs) const ctx = await debounce.identify?.( new Context({ type: 'identify', userId: 'hasbulla', anonymousId: 'the goat', traits: {} }) ) expect(ctx.event.integrations['Braze Web Mode (Actions)']).toBe(true) }) test('does not send the event to braze if IDs are the same', async () => { const [debounce] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions: [ { partnerAction: 'debounce', name: 'Debounce', enabled: true, subscribe: 'type = "identify"', mapping: {} } ] }) await ajs.register(debounce) const ctx = await ajs.identify('hasbulla', { goat: true }) expect(ctx.event.integrations['Braze Web Mode (Actions)']).toBe(true) const secondCtx = await ajs.identify('hasbulla', { goat: true }) expect(secondCtx.event.integrations['Braze Web Mode (Actions)']).toBe(false) }) test('ignores blank anonymous ids', async () => { const [debounce] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions: [ { partnerAction: 'debounce', name: 'Debounce', enabled: true, subscribe: 'type = "identify"', mapping: {} } ] }) await ajs.register(debounce) const ctx = await ajs.identify() expect(ctx.event.integrations['Braze Web Mode (Actions)']).toBe(true) const secondCtx = await ajs.identify() expect(secondCtx.event.integrations['Braze Web Mode (Actions)']).toBe(false) }) test('send events on trait changes', async () => { const [debounce] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions: [ { partnerAction: 'debounce', name: 'Debounce', enabled: true, subscribe: 'type = "identify"', mapping: {} } ] }) await ajs.register(debounce) const ctx = await ajs.identify('hasbulla', { goat: true }) expect(ctx.event.integrations['Braze Web Mode (Actions)']).toBe(true) const sameCtx = await ajs.identify('hasbulla', { goat: true }) expect(sameCtx.event.integrations['Braze Web Mode (Actions)']).toBe(false) const changedTraits = await ajs.identify('hasbulla', { weight: 'feather' }) expect(changedTraits.event.integrations['Braze Web Mode (Actions)']).toBe(true) }) })
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/createUpdateDevice/index.ts
import dayjs from '../../../lib/dayjs' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Create or Update Device', description: "Update a person's device in Customer.io or create it if it doesn't exist.", defaultSubscription: 'type = "track" and event = "Application Installed"', fields: { person_id: { label: 'Person ID', description: 'ID of the person that this device belongs to.', type: 'string', required: true, default: { '@path': '$.userId' } }, device_id: { label: 'Device ID', description: 'Unique ID for this device.', type: 'string', required: true, default: { '@path': '$.context.device.id' } }, platform: { label: 'Platform', description: 'The device platform.', type: 'string', required: true, // enum: ['ios', 'android'], default: { '@path': '$.context.device.type' } }, last_used: { label: 'Last Used', description: 'Timestamp for when the device was last used. Default is current date and time.', type: 'string', default: { '@path': '$.timestamp' } } }, perform: (request, { payload }) => { return request(`https://track.customer.io/api/v1/customers/${payload.person_id}/devices`, { method: 'put', json: { device: { id: payload.device_id, platform: payload.platform, last_used: payload.last_used ? dayjs.utc(payload.last_used).format('X') : undefined } } }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-enhanced-conversions/postConversion/index.ts
import { ActionDefinition, IntegrationError } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' import { formatCity, formatEmail, formatFirstName, formatLastName, formatPhone, formatStreet, formatRegion, cleanData } from './formatter' const action: ActionDefinition<Settings, Payload> = { title: 'Post Conversion', description: 'Send a conversion event to Google Ads.', fields: { // Required Fields - These fields are required by Google's EC API to successfully match conversions. conversion_label: { label: 'Conversion Label', description: 'The Google Ads conversion label. You can find this value from your Google Ads event snippet. The provided event snippet should have, for example, `send_to: AW-123456789/AbC-D_efG-h12_34-567`. Enter the part after the forward slash, without the AW- prefix, e.g. 123456789', type: 'string', required: true, default: '' }, email: { label: 'Email', description: 'Email address of the customer who triggered the conversion event.', type: 'string', required: true, format: 'email', default: { '@if': { exists: { '@path': '$.properties.email' }, then: { '@path': '$.properties.email' }, else: { '@path': '$.traits.email' } } } }, transaction_id: { label: 'Order ID', description: 'Order ID of the conversion event. Google requires an Order ID even if the event is not an ecommerce event.', type: 'string', required: true, default: { '@path': '$.properties.orderId' } }, user_agent: { label: 'User Agent', description: 'User Agent of the customer who triggered the conversion event.', type: 'string', required: true, default: { '@path': '$.context.userAgent' } }, conversion_time: { label: 'Conversion Time', description: 'Timestamp of the conversion event.', type: 'datetime', required: true, default: { '@path': '$.timestamp' } }, // Conversion Data Fields - These fields are relevant to the conversion, but are not PII, so need not be hashed. value: { label: 'Value', description: 'The monetary value attributed to the conversion event.', type: 'number', default: { '@path': '$.properties.total' } }, currency_code: { label: 'Currency Code', description: 'Currency of the purchase or items associated with the event, in 3-letter ISO 4217 format.', type: 'string', default: { '@path': '$.properties.currency' } }, // PII Fields - These fields must be hashed using SHA 256 and encoded as websafe-base64. phone_number: { label: 'Phone Number', description: 'Phone number of the purchaser, in E.164 standard format, e.g. +14150000000', type: 'string', default: { '@if': { exists: { '@path': '$.properties.phone' }, then: { '@path': '$.properties.phone' }, else: { '@path': '$.traits.phone' } } } }, first_name: { label: '<NAME>', description: 'First name of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.firstName' }, then: { '@path': '$.properties.firstName' }, else: { '@path': '$.traits.firstName' } } } }, last_name: { label: '<NAME>', description: 'Last name of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.lastName' }, then: { '@path': '$.properties.lastName' }, else: { '@path': '$.traits.lastName' } } } }, street_address: { label: 'Street Address', description: 'Street address of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.address.street' }, then: { '@path': '$.properties.address.street' }, else: { '@path': '$.traits.address.street' } } } }, city: { label: 'City', description: 'City of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.address.city' }, then: { '@path': '$.properties.address.city' }, else: { '@path': '$.traits.address.city' } } } }, region: { label: 'Region', description: 'Region of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.address.state' }, then: { '@path': '$.properties.address.state' }, else: { '@path': '$.traits.address.state' } } } }, post_code: { label: 'Post Code', description: 'Post code of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.address.postalCode' }, then: { '@path': '$.properties.address.postalCode' }, else: { '@path': '$.traits.address.postalCode' } } } }, country: { label: 'Country', description: 'Country of the individual who triggered the conversion event.', type: 'string', default: { '@if': { exists: { '@path': '$.properties.address.country' }, then: { '@path': '$.properties.address.country' }, else: { '@path': '$.traits.address.country' } } } } }, perform: (request, { payload }) => { const conversionData = cleanData({ oid: payload.transaction_id, user_agent: payload.user_agent, conversion_time: +new Date(payload.conversion_time) * 1000, label: payload.conversion_label, value: payload.value, currency_code: payload.currency_code }) const address = cleanData({ hashed_first_name: formatFirstName(payload.first_name), hashed_last_name: formatLastName(payload.last_name), hashed_street_address: formatStreet(payload.street_address), city: formatCity(payload.city), region: formatRegion(payload.region), postcode: payload.post_code, country: payload.country }) if (!payload.email && !Object.keys(address).length) { throw new IntegrationError( 'Either a valid email address or at least one address property (firstName, lastName, street, city, region, postalCode, or country) is required to send a valid conversion.', 'Missing required fields.', 400 ) } const pii_data = cleanData({ hashed_email: formatEmail(payload.email), hashed_phone_number: [formatPhone(payload.phone_number)] }) return request('https://www.google.com/ads/event/api/v1', { method: 'post', json: { pii_data: { ...pii_data, address: [address] }, ...conversionData } }) } } export default action
jbwyme/action-destinations
packages/cli/src/lib/destinations.ts
<filename>packages/cli/src/lib/destinations.ts import type { DestinationDefinition as CloudDestinationDefinition } from '@segment/actions-core' import type { BrowserDestinationDefinition } from '@segment/browser-destinations' import path from 'path' import { clearRequireCache } from './require-cache' import { OAUTH_SCHEME } from '../constants' export type DestinationDefinition = CloudDestinationDefinition | BrowserDestinationDefinition /** * Attempts to load a destination definition from a given file path * Note: this requires ts-node when loading .ts files */ export async function loadDestination(filePath: string): Promise<null | DestinationDefinition> { const importPath = path.isAbsolute(filePath) ? filePath : path.join(process.cwd(), filePath) // Clear Node's require cache to pick up any changes clearRequireCache() // Import the file, assert that it's a destination definition entrypoint // eslint-disable-next-line @typescript-eslint/no-var-requires const module = require(importPath) // look for `default` or `destination` export const destination = module.destination || module.default // Loose validation on a destination definition if (!destination?.name || typeof destination?.actions !== 'object') { return null } return destination } export function hasOauthAuthentication(definition: DestinationDefinition): boolean { return ( 'authentication' in definition && !!definition.authentication && 'scheme' in definition.authentication && definition.authentication.scheme === OAUTH_SCHEME ) }
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/trackEvent/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * ID of the person who triggered this event. */ id?: string /** * Anonymous ID of the person who triggered this event. */ anonymous_id?: string /** * Name of the event */ name: string /** * Override event type. Ex. "page". */ type?: string /** * Custom data to include with the event. */ data?: { [k: string]: unknown } }
jbwyme/action-destinations
packages/destination-actions/src/destinations/pipedrive/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * Pipedrive domain. This is found in Pipedrive in Settings > Company settings > Company domain. */ domain: string /** * Pipedrive API token. This is found in Pipedrive in Settings > Personal preferences > API > Your personal API token. */ apiToken: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/pipedrive/createUpdatePerson/index.ts
import dayjs from '../../../lib/dayjs' import { get } from '@segment/actions-core' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' interface Organizations { data: Organization[] additional_data: { pagination: { next_start?: number } } } interface Organization { id: string name: string } interface Person { name: string org_id?: number email?: string[] phone?: string add_time?: string } const action: ActionDefinition<Settings, Payload> = { title: 'Create or Update Person', description: "Update a person in Pipedrive or create them if they don't exist yet.", defaultSubscription: 'type = "identify"', fields: { identifier: { label: 'Person ID', description: 'Identifier used to find existing person in Pipedrive. Can be an email, name, phone number, or custom field value. Custom person fields may be included by using the long hash keys of the custom fields. These look like "33595c732cd7a027c458ea115a48a7f8a254fa86".', type: 'string', required: true, default: { '@path': '$.userId' } }, name: { label: 'Person Name', description: 'Name of the person', type: 'string', required: true }, org_id: { label: 'Organization ID', description: 'ID of the organization this person will belong to.', type: 'number', dynamic: true }, email: { label: 'Email Address', description: 'Email addresses for this person.', type: 'string', multiple: true }, phone: { label: 'Phone Number', description: 'Phone number for the person.', type: 'string' }, add_time: { label: 'Created At', description: 'If the person is created, use this timestamp as the creation timestamp. Format: YYY-MM-DD HH:MM:SS', type: 'string' } }, dynamicFields: { org_id: async (request, { page, settings }) => { const searchParams: Record<string, number> = {} if (typeof page === 'string') { searchParams.start = Number(page) } const response = await request<Organizations>(`https://${settings.domain}.pipedrive.com/api/v1/organizations`, { searchParams }) const body = response.data const items = body.data.map((organization) => ({ label: organization.name, value: organization.id })) let nextPage: string | undefined if (typeof body.additional_data.pagination.next_start === 'number') { nextPage = String(body.additional_data.pagination.next_start) } return { body: { data: items, pagination: { nextPage } } } } }, perform: async (request, { payload, settings }) => { const search = await request(`https://${settings.domain}.pipedrive.com/api/v1/persons/search`, { searchParams: { term: payload.identifier } }) const personId = get(search.data, 'data.items[0].item.id') const person: Person = { name: payload.name, org_id: payload.org_id, email: payload.email, phone: payload.phone } if (personId === undefined || personId === null) { if (payload.add_time) { person.add_time = dayjs.utc(person.add_time).format('YYYY-MM-DD HH:MM:SS') } return request(`https://${settings.domain}.pipedrive.com/api/v1/persons`, { method: 'post', json: person }) } return request(`https://${settings.domain}.pipedrive.com/api/v1/persons/${personId}`, { method: 'put', json: person }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-twilio/index.ts
import type { DestinationDefinition } from '@segment/actions-core' import type { Settings } from './generated-types' import sendSms from './sendSms' const destination: DestinationDefinition<Settings> = { name: 'Actions Personas Messaging Twilio', mode: 'cloud', authentication: { scheme: 'custom', fields: { twilioAccountId: { label: 'Twilio Account ID', description: 'Twilio Account ID', type: 'string', required: true }, twilioAuthToken: { label: 'Twilio Auth Token', description: 'Twilio Auth Token', type: 'password', required: true }, profileApiEnvironment: { label: 'Profile API Environment', description: 'Profile API Environment', type: 'string', required: true }, profileApiAccessToken: { label: 'Profile API Access Token', description: 'Profile API Access Token', type: 'password', required: true }, spaceId: { label: 'Space ID', description: 'Space ID', type: 'string', required: true }, sourceId: { label: 'Source ID', description: 'Source ID', type: 'string', required: true } }, testAuthentication: (request) => { return request('https://api.twilio.com/2010-04-01') } }, // TODO: GROW-259 we'll uncomment this once we remove the calls to the profiles API, // but for now this would extend those requests and result in 401s // extendRequest: ({ settings }) => { // return { // username: settings.twilioAccountId, // password: settings.twilioAuthToken // } // }, actions: { sendSms } } export default destination
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-sendgrid/generated-types.ts
<reponame>jbwyme/action-destinations<filename>packages/destination-actions/src/destinations/personas-messaging-sendgrid/generated-types.ts // Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * The Api Key for your sendGrid account */ sendGridApiKey: string /** * Profile API Environment */ profileApiEnvironment: string /** * Profile API Access Token */ profileApiAccessToken: string /** * Space ID */ spaceId: string /** * Source ID */ sourceId: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-sendgrid/__tests__/send-email.test.ts
<gh_stars>0 import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import Sendgrid from '..' const sendgrid = createTestIntegration(Sendgrid) const timestamp = new Date().toISOString() for (const environment of ['stage', 'production']) { const settings = { sendGridApiKey: 'sendGridApiKey', profileApiEnvironment: environment, profileApiAccessToken: 'c', spaceId: 'spaceId', sourceId: 'sourceId' } const endpoint = `https://profiles.segment.${environment === 'production' ? 'com' : 'build'}` describe(`${environment} - send Email`, () => { it('should send Email', async () => { nock(`${endpoint}/v1/spaces/spaceId/collections/users/profiles/user_id:jane`) .get('/traits?limit=200') .reply(200, { traits: { firstName: '<NAME>', lastName: 'Browning' } }) nock(`${endpoint}/v1/spaces/spaceId/collections/users/profiles/user_id:jane`) .get('/external_ids?limit=25') .reply(200, { data: [ { type: 'user_id', id: 'jane' }, { type: 'phone', id: '+1234567891' }, { type: 'email', id: '<EMAIL>' } ] }) const expectedSendGridRequest = { personalizations: [ { to: [ { email: '<EMAIL>', name: '<NAME>' } ], bcc: [ { email: '<EMAIL>' } ], custom_args: { source_id: 'sourceId', space_id: 'spaceId', user_id: 'jane' } } ], from: { email: '<EMAIL>', name: '<NAME>' }, reply_to: { email: '<EMAIL>', name: '<NAME>' }, subject: 'Hello Browning First Name.', content: [ { type: 'text/html', value: 'Hi First Name, Welcome to segment' } ] } const sendGridRequest = nock('https://api.sendgrid.com') .post('/v3/mail/send', expectedSendGridRequest) .reply(200, {}) const responses = await sendgrid.testAction('sendEmail', { event: createTestEvent({ timestamp, event: 'Audience Entered', userId: 'jane' }), settings, mapping: { userId: { '@path': '$.userId' }, fromEmail: '<EMAIL>', fromName: '<NAME>', replyToEmail: '<EMAIL>', replyToName: 'Test user', bcc: JSON.stringify([ { email: '<EMAIL>' } ]), previewText: '', subject: 'Hello {{profile.traits.lastName}} {{profile.traits.firstName}}.', body: 'Hi {{profile.traits.firstName}}, Welcome to segment', bodyType: 'html', bodyHtml: 'Hi {{profile.traits.firstName}}, Welcome to segment' } }) expect(responses.length).toEqual(3) expect(sendGridRequest.isDone()).toEqual(true) }) }) }
jbwyme/action-destinations
packages/core/src/request-client.ts
<gh_stars>0 import AbortController from 'abort-controller' import { CustomError } from 'ts-custom-error' import { URL, URLSearchParams } from 'url' import fetch, { Headers, Request, Response } from './fetch' import { isObject } from './real-type-of' /** * The supported request options you can use with the request client */ export interface RequestOptions extends Omit<RequestInit, 'headers'> { /** * Simplified header format to reduce variation */ headers?: Record<string, string> /** * Shortcut for sending JSON. Use instead of `body`. * Accepts any plain object or value, which will be `JSON.stringify()`'d and sent in the body with the correct header set. */ json?: unknown /** * HTTP method used to make the request. * Internally, the standard methods (`GET`, `POST`, `PUT`, `PATCH`, `HEAD` and `DELETE`) are uppercased in order to avoid server errors due to case sensitivity. * @default 'get' */ method?: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'head' | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' /** * When provided, will automatically apply basic authentication */ password?: string /** * Search parameters to include int he request URL. Setting this will override existing search parameters in the input URL. * Accepts [`URLSearchParams()`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams) */ searchParams?: URLSearchParams | Record<string, string | number | boolean> /** * Throw an error when, after redirects, the response has a non-2xx status code. * @default true */ throwHttpErrors?: boolean /** * Timeout in milliseconds for getting a response. * If set to `false` there will be no timeout. * @default 10000 */ timeout?: number | false /** * When provided, will automatically apply basic authentication */ username?: string } /** * All request options including before/after hooks */ export interface AllRequestOptions extends RequestOptions { /** * Hooks that execute before a request is sent. * Useful to modify the options that a request will use */ beforeRequest?: BeforeRequestHook[] /** * Hooks that executes after a response is received. * Useful for logging, cleanup, or modifying the response object */ afterResponse?: AfterResponseHook[] } export interface NormalizedOptions extends Omit<AllRequestOptions, 'headers'> { // the merging process turns these into a Headers object, but you can pass in more headers: RequestInit['headers'] // method is expected to be defined at this point method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' } type MaybePromise<T> = Promise<T> | T /** A hook that executes before a request is executed. Useful to modify the options that a request will use */ export type BeforeRequestHook = (options: NormalizedOptions) => MaybePromise<RequestOptions | void> /** A hook that executes after a response is received. Useful for logging, cleanup, or modifying the response object */ export type AfterResponseHook<OutputResponse extends Response = Response> = ( request: Request, options: NormalizedOptions, response: Response ) => MaybePromise<OutputResponse | void> // We need the loose definition of "object" to iterate over things like `[object Headers]` const isObjectLike = (value: unknown): value is { [key: string]: unknown } => { return value !== null && typeof value === 'object' } /** Merges two sets of headers intelligently */ function mergeHeaders(source1: RequestInit['headers'], source2: RequestInit['headers']) { const result = new Headers(source1 || {}) const source = new Headers(source2 || {}) source.forEach((value, key) => { // `value` may be the string `undefined` when the source is a Headers object if (value === 'undefined') { result.delete(key) } else { result.set(key, value) } }) return result } /** Deeply merge multiple objects or arrays. Arrays get concatenated. */ function merge<T>(...sources: T[]): T { // eslint-disable-next-line @typescript-eslint/no-explicit-any let result: any = {} let headers: RequestInit['headers'] = {} for (const source of sources) { if (Array.isArray(source)) { if (!Array.isArray(result)) { result = [] } // Concatenate arrays (e.g. hooks) result = [...result, ...source] } else if (isObjectLike(source)) { // eslint-disable-next-line prefer-const for (let [key, value] of Object.entries(source)) { // Recurse over objects if (isObjectLike(value) && key in result) { value = merge(result[key], value) } // Update the key's value in our copy result[key] = value } // Merge headers more carefully to handle duplicates if (isObjectLike(source.headers)) { headers = mergeHeaders(headers, source.headers as RequestInit['headers']) } } // Assign after we've merged all the headers because they are handled specially result.headers = headers } return result as T } /** * Validates and merges request options */ function mergeOptions(...sources: Array<NormalizedOptions | AllRequestOptions>): AllRequestOptions { for (const source of sources) { if (!isObject(source)) { throw new TypeError(`The 'options' argument must be an object`) } } return merge({}, ...sources) as AllRequestOptions } function getRequestMethod<T extends string>(method: T): T { return method.toUpperCase() as T } /** Error thrown when a response has a non-2xx response. */ export class HTTPError extends CustomError { request: Request response: Response options: NormalizedOptions constructor(response: Response, request: Request, options: NormalizedOptions) { super(response.statusText ?? String(response.status ?? 'Unknown response error')) this.response = response this.request = request this.options = options } } /** Error thrown when a request is aborted because of a client timeout. */ export class TimeoutError extends CustomError { request: Request options: NormalizedOptions constructor(request: Request, options: NormalizedOptions) { super(`Request timed out`) this.request = request this.options = options } } /** * Given a request, reject the request when a timeout is exceeded */ function timeoutFetch( request: Request, abortController: AbortController, options: NormalizedOptions ): Promise<Response> { return new Promise((resolve, reject) => { const timer = setTimeout(() => { if (abortController) { abortController.abort() } reject(new TimeoutError(request, options)) }, options.timeout as number) void fetch(request) .then(resolve) .catch(reject) .then(() => clearTimeout(timer)) }) } class RequestClient { private abortController: AbortController private request: Request private options: NormalizedOptions constructor(url: string, options: AllRequestOptions = {}) { this.setOptions(url, options) } private setOptions(url: string, options: AllRequestOptions) { this.options = { ...options, method: getRequestMethod(options.method ?? 'get'), throwHttpErrors: options.throwHttpErrors !== false, timeout: options.timeout ?? 10000 } as NormalizedOptions // Timeout support. Use our own abort controller so consumers can pass in their own `signal` // if they wish to use timeouts alongside other logic to abort a request this.abortController = new AbortController() if (this.options.signal) { // Listen to consumer abort events to also abort our internal controller this.options.signal.addEventListener('abort', () => { this.abortController.abort() }) } // Use our internal abort controller for fetch this.options.signal = this.abortController.signal // Construct a request object to send to the Fetch API this.request = new Request(url, this.options) // Parse search params and merge them with the request URL if (this.options.searchParams) { // The type is a bit too restrictive, since you can pass in other primitives like `{ foo: 1, bar: true }` const searchParams = new URLSearchParams(this.options.searchParams as URLSearchParams | Record<string, string>) const url = new URL(this.request.url) url.search = searchParams.toString() // Update the request object with the new url including the search params this.request = new Request(new Request(url.toString(), this.request), this.options) } // Automatically handle json header + stringification as a convenience when using `json` option if (this.options.json !== undefined) { this.options.body = JSON.stringify(this.options.json) this.request.headers.set('content-type', 'application/json') this.request = new Request(this.request, { body: this.options.body }) } } async executeRequest<T extends Response>(): Promise<T> { let response = await this.fetch() for (const hook of this.options.afterResponse ?? []) { const modifiedResponse = await hook(this.request, this.options, response) if (modifiedResponse instanceof Response) { response = modifiedResponse } } if (!response.ok && this.options.throwHttpErrors) { throw new HTTPError(response, this.request, this.options) } return response as T } /** * Make a fetch request, running all beforeRequest hooks, and optionally wrap in a timeout */ private async fetch() { for (const hook of this.options.beforeRequest ?? []) { const newOptions = await hook({ ...this.options }) if (newOptions && isObject(newOptions)) { this.setOptions(this.request.url, mergeOptions(this.options, newOptions)) } } if (this.options.timeout === false) { return fetch(this.request.clone()) } return timeoutFetch(this.request.clone(), this.abortController, this.options) } } /** * Creates a new instance of the fetch request client, * optionally with default configuration to apply to all requests made with the client */ export default function createInstance(defaults: AllRequestOptions = {}) { const client = <R extends Response = Response>(url: string, options: RequestOptions = {}) => new RequestClient(url, mergeOptions(defaults, options)).executeRequest<R>() client.extend = (newDefaults: AllRequestOptions) => createInstance(mergeOptions(defaults, newDefaults)) return client }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/fullstory/generated-types.ts
<gh_stars>0 // Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * The organization ID for FullStory */ orgId: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/amplitude/mapUser/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * The User ID to be associated */ user_id?: string /** * The global User ID to associate to */ global_user_id?: string /** * Amplitude has a default minimum id lenght of 5 characters for user_id and device_id fields. This field allows the minimum to be overridden to allow shorter id lengths. */ min_id_length?: number | null }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/__tests__/trackPurchase.test.ts
import appboy from '@braze/web-sdk' import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import brazeDestination from '../index' beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://segment.com' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) }) beforeEach(() => { // we're not really testing that appboy loads here, so we'll just mock it out jest.spyOn(appboy, 'initialize').mockImplementation(() => true) jest.spyOn(appboy, 'openSession').mockImplementation(() => true) }) test('reports products when present', async () => { const brazeLogPurchase = jest.spyOn(appboy, 'logPurchase').mockReturnValue(true) const [trackPurchase] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', sdkVersion: '3.3', subscriptions: [ { partnerAction: 'trackPurchase', name: 'Log Purchase', enabled: true, subscribe: 'type = "track"', mapping: { purchaseProperties: { '@path': '$.properties' }, products: { '@path': '$.properties.products' } } } ] }) await trackPurchase.load(Context.system(), {} as Analytics) await trackPurchase.track?.( new Context({ type: 'track', properties: { banana: 'yellow', products: [ { product_id: 'p_123', price: 399, currency: 'BGP', quantity: 2 }, { product_id: 'p_456', price: 0 } ] } }) ) expect(brazeLogPurchase.mock.calls[0]).toMatchInlineSnapshot(` Array [ "p_123", 399, "BGP", 2, Object { "banana": "yellow", "products": Array [ Object { "currency": "BGP", "price": 399, "product_id": "p_123", "quantity": 2, }, Object { "price": 0, "product_id": "p_456", }, ], }, ] `) // applying defaults expect(brazeLogPurchase.mock.calls[1]).toMatchInlineSnapshot(` Array [ "p_456", 0, "USD", 1, Object { "banana": "yellow", "products": Array [ Object { "currency": "BGP", "price": 399, "product_id": "p_123", "quantity": 2, }, Object { "price": 0, "product_id": "p_456", }, ], }, ] `) })
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-sendgrid/sendEmail/generated-types.ts
<gh_stars>0 // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * User ID in Segment */ userId: string /** * Email to send to when testing */ toEmail?: string /** * From Email */ fromEmail: string /** * From Name displayed to end user email */ fromName: string /** * The Email used by user to Reply To */ replyToEmail: string /** * The Name used by user to Reply To */ replyToName: string /** * BCC list of emails */ bcc: string /** * Preview Text */ previewText: string /** * Subject for the email to be sent */ subject: string /** * The message body */ body: string /** * The type of body which is used generally html | design */ bodyType: string /** * The HTML content of the body */ bodyHtml: string }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/index.ts
<reponame>jbwyme/action-destinations import type { Settings } from './generated-types' import type { BrowserDestinationDefinition } from '../../lib/browser-destinations' import { browserDestination } from '../../runtime/shim' import appboy from '@braze/web-sdk' import trackEvent from './trackEvent' import updateUserProfile from './updateUserProfile' import trackPurchase from './trackPurchase' import debounce, { resetUserCache } from './debounce' import { defaultValues, DestinationDefinition } from '@segment/actions-core' declare global { interface Window { appboy: typeof appboy } } const presets: DestinationDefinition['presets'] = [ { name: 'Identify Calls', subscribe: 'type = "identify" or type = "group"', partnerAction: 'updateUserProfile', mapping: defaultValues(updateUserProfile.fields) }, { name: 'Order Completed calls', subscribe: 'type = "track" and event = "Order Completed"', partnerAction: 'trackPurchase', mapping: defaultValues(trackPurchase.fields) }, { name: 'Track Calls', subscribe: 'type = "track" and event != "Order Completed"', partnerAction: 'trackEvent', mapping: { ...defaultValues(trackEvent.fields), eventName: { '@path': '$.event' }, eventProperties: { '@path': '$.properties' } } } ] export const destination: BrowserDestinationDefinition<Settings, typeof appboy> = { name: 'Braze Web Mode', slug: 'actions-braze-web', mode: 'device', settings: { sdkVersion: { description: 'The version of the SDK to use. Defaults to 3.3.', label: 'SDK Version', type: 'string', choices: [ { value: '3.3', label: '3.3' } ], default: '3.3', required: true }, api_key: { description: 'Found in the Braze Dashboard under Settings → Manage Settings → Apps → Web', label: 'API Key', type: 'password', required: true }, endpoint: { label: 'SDK Endpoint', description: 'Your Braze SDK endpoint. [See more details](https://www.braze.com/docs/user_guide/administrative/access_braze/sdk_endpoints/)', type: 'string', format: 'uri', choices: [ { label: 'US-01 (https://dashboard-01.braze.com)', value: 'sdk.iad-01.braze.com' }, { label: 'US-02 (https://dashboard-02.braze.com)', value: 'sdk.iad-02.braze.com' }, { label: 'US-03 (https://dashboard-03.braze.com)', value: 'sdk.iad-03.braze.com' }, { label: 'US-04 (https://dashboard-04.braze.com)', value: 'sdk.iad-04.braze.com' }, { label: 'US-05 (https://dashboard-05.braze.com)', value: 'sdk.iad-05.braze.com' }, { label: 'US-06 (https://dashboard-06.braze.com)', value: 'sdk.iad-06.braze.com' }, { label: 'US-08 (https://dashboard-08.braze.com)', value: 'sdk.iad-08.braze.com' }, { label: 'EU-01 (https://dashboard-01.braze.eu)', value: 'sdk.fra-01.braze.eu' } ], default: 'sdk.iad-01.braze.com', required: true }, allowCrawlerActivity: { description: 'Allow Braze to log activity from crawlers. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)', label: 'Allow Crawler Activity', default: false, type: 'boolean', required: false }, allowUserSuppliedJavascript: { description: 'To indicate that you trust the Braze dashboard users to write non-malicious Javascript click actions, set this property to true. If enableHtmlInAppMessages is true, this option will also be set to true. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)', label: 'Allow User Supplied Javascript', default: false, type: 'boolean', required: false }, appVersion: { description: 'Version to which user events sent to Braze will be associated with. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)', label: 'App Version', type: 'string', required: false }, contentSecurityNonce: { description: 'Allows Braze to add the nonce to any <script> and <style> elements created by the SDK. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)', label: 'Content Security nonce', type: 'string', required: false }, devicePropertyAllowlist: { label: 'Device Property Allow List', description: 'By default, the Braze SDK automatically detects and collects all device properties in DeviceProperties. To override this behavior, provide an array of DeviceProperties. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)', type: 'string', required: false, multiple: true }, disablePushTokenMaintenance: { label: 'Disable Push Token Maintenance', type: 'boolean', default: true, required: false, description: 'By default, users who have already granted web push permission will sync their push token with the Braze backend automatically on new session to ensure deliverability. To disable this behavior, set this option to false' }, doNotLoadFontAwesome: { label: 'Do Not Load Font Awesome', type: 'boolean', default: false, description: 'Braze automatically loads FontAwesome 4.7.0 from the FontAwesome CDN. To disable this behavior set this option to true.' }, enableLogging: { label: 'Enable Logging', required: false, default: false, type: 'boolean', description: 'Set to true to enable logging by default' }, enableSdkAuthentication: { label: 'Enable SDK Authentication', type: 'boolean', required: false, default: false, description: 'Set to true to enable the SDK Authentication feature.' }, inAppMessageZIndex: { label: 'In-App Message Z Index', type: 'number', required: false, description: "By default, the Braze SDK will show In-App Messages with a z-index of 1040 for the screen overlay, 1050 for the actual in-app message, and 1060 for the message's close button. Provide a value for this option to override these default z-indexes." }, localization: { label: 'Localization', type: 'string', default: 'en', required: false, description: "By default, any SDK-generated user-visible messages will be displayed in the user's browser language. Provide a value for this option to override that behavior and force a specific language. The value for this option should be a ISO 639-1 Language Code." }, manageServiceWorkerExternally: { label: 'Manage Service Worker Externally', type: 'boolean', default: false, required: false, description: 'If you have your own service worker that you register and control the lifecycle of, set this option to true and the Braze SDK will not register or unregister a service worker. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)' }, minimumIntervalBetweenTriggerActionsInSeconds: { label: 'Minimum Interval Between Trigger Actions in Seconds', type: 'number', required: false, default: 30, description: 'Provide a value to override the default interval between trigger actions with a value of your own. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)' }, noCookies: { label: 'No Cookies', type: 'boolean', default: false, required: false, description: 'By default, the Braze SDK will store small amounts of data (user ids, session ids), in cookies. Pass true for this option to disable cookie storage and rely entirely on HTML 5 localStorage to identify users and sessions. [See more details](https://js.appboycdn.com/web-sdk/latest/doc/modules/appboy.html#initializationoptions)' }, openCardsInNewTab: { label: 'Open Cards In New Tab', type: 'boolean', default: false, required: false, description: 'By default, links from Card objects load in the current tab or window. Set this option to true to make links from cards open in a new tab or window.' }, openInAppMessagesInNewTab: { label: 'Open In-App Messages In New Tab', type: 'boolean', default: false, required: false, description: 'By default, links from in-app message clicks load in the current tab or a new tab as specified in the dashboard on a message-by-message basis. Set this option to true to force all links from in-app message clicks open in a new tab or window.' }, requireExplicitInAppMessageDismissal: { label: 'Require Explicit In-App Message Dismissal', type: 'boolean', required: false, default: false, description: 'By default, when an in-app message is showing, pressing the escape button or a click on the greyed-out background of the page will dismiss the message. Set this option to true to prevent this behavior and require an explicit button click to dismiss messages.' }, safariWebsitePushId: { label: 'Safari Website Push ID', type: 'string', required: false, description: 'If you support Safari push, you must specify this option with the website push ID that you provided to Apple when creating your Safari push certificate (starts with "web", e.g. "web.com.example.domain").' }, serviceWorkerLocation: { label: 'Service Worker Location', type: 'string', required: false, description: 'By default, when registering users for web push notifications Braze will look for the required service worker file in the root directory of your web server at /service-worker.js. If you want to host your service worker at a different path on that server, provide a value for this option that is the absolute path to the file, e.g. /mycustompath/my-worker.js. VERY IMPORTANT: setting a value here limits the scope of push notifications on your site. For instance, in the above example, because the service ,worker file is located within the /mycustompath/ directory, appboy.registerAppboyPushMessages MAY ONLY BE CALLED from web pages that start with http://yoursite.com/mycustompath/.' }, sessionTimeoutInSeconds: { label: 'Session Timeout in Seconds', type: 'number', default: 1800, // 30 minutes required: false, description: 'By default, sessions time out after 30 minutes of inactivity. Provide a value for this configuration option to override that default with a value of your own.' } }, initialize: async ({ settings }, dependencies) => { const { endpoint, api_key, ...expectedConfig } = settings const sdkVersion = settings.sdkVersion?.length ? settings.sdkVersion : '3.3' await dependencies.loadScript(`https://js.appboycdn.com/web-sdk/${sdkVersion}/service-worker.js`) const initialized = appboy.initialize(settings.api_key, { baseUrl: endpoint, ...expectedConfig }) if (!initialized) { throw new Error('Failed to initialize AppBoy') } appboy.openSession() resetUserCache() return appboy }, presets, actions: { updateUserProfile, trackEvent, trackPurchase, debounce } } export default browserDestination(destination)
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/__tests__/purchase.test.ts
<gh_stars>0 import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import ga4 from '../index' const testDestination = createTestIntegration(ga4) const apiSecret = '<KEY>' const measurementId = 'G-TESTTOKEN' describe('GA4', () => { describe('Purchase', () => { it('should handle basic mapping overrides', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Order Completed', userId: '3456fff', anonymousId: 'anon-567890', type: 'track', properties: { affiliation: 'TI Online Store', order_id: '5678dd9087-78', coupon: 'SUMMER_FEST', currency: 'EUR', products: [ { product_id: 'pid-123456', sku: 'SKU-123456', name: 'Tour t-shirt', quantity: 2, coupon: 'MOUNTAIN', brand: 'Canvas', category: 'T-Shirt', variant: 'Black', price: 19.98 } ], revenue: 5.99, shipping: 1.5, tax: 3.0, total: 24.48 } }) const responses = await testDestination.testAction('purchase', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.anonymousId' }, coupon: { '@path': '$.properties.coupon' }, currency: { '@path': '$.properties.currency' }, transaction_id: { '@path': '$.properties.order_id' }, value: { '@path': '$.properties.revenue' }, items: [ { item_name: { '@path': `$.properties.products.0.name` }, item_id: { '@path': `$.properties.products.0.product_id` }, quantity: { '@path': `$.properties.products.0.quantity` }, coupon: { '@path': `$.properties.products.0.coupon` }, item_brand: { '@path': `$.properties.products.0.brand` }, item_category: { '@path': `$.properties.products.0.category` }, item_variant: { '@path': `$.properties.products.0.variant` }, price: { '@path': `$.properties.products.0.price` } } ] }, useDefaultMappings: false }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(201) expect(responses[0].request.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "content-type": Array [ "application/json", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.body).toMatchInlineSnapshot( `"{\\"client_id\\":\\"anon-567890\\",\\"events\\":[{\\"name\\":\\"purchase\\",\\"params\\":{\\"coupon\\":\\"SUMMER_FEST\\",\\"currency\\":\\"EUR\\",\\"items\\":[{\\"item_name\\":\\"Tour t-shirt\\",\\"item_id\\":\\"pid-123456\\",\\"quantity\\":2,\\"coupon\\":\\"MOUNTAIN\\",\\"item_brand\\":\\"Canvas\\",\\"item_category\\":\\"T-Shirt\\",\\"item_variant\\":\\"Black\\",\\"price\\":19.98}],\\"transaction_id\\":\\"5678dd9087-78\\",\\"value\\":5.99}}]}"` ) }) it('should throw an error for invalid currency values', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Order Completed', userId: '3456fff', type: 'track', properties: { order_id: '5678dd9087-78', coupon: 'SUMMER_FEST', currency: '1234' } }) try { await testDestination.testAction('purchase', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.userId' }, coupon: { '@path': '$.properties.coupon' }, currency: { '@path': '$.properties.currency' }, transaction_id: { '@path': '$.properties.order_id' } }, useDefaultMappings: true }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe('1234 is not a valid currency code.') } }) it('should throw error when product name and id are missing', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Order Completed', userId: '3456fff', anonymousId: 'anon-567890', type: 'track', properties: { affiliation: 'TI Online Store', order_id: '5678dd9087-78', coupon: 'SUMMER_FEST', currency: 'EUR', products: [ { quantity: 2, coupon: 'MOUNTAIN', brand: 'Canvas', category: 'T-Shirt', variant: 'Black', price: 19.98 } ], revenue: 5.99, shipping: 1.5, tax: 3.0, total: 24.48 } }) try { await testDestination.testAction('purchase', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.anonymousId' }, coupon: { '@path': '$.properties.coupon' }, currency: { '@path': '$.properties.currency' }, transaction_id: { '@path': '$.properties.order_id' }, value: { '@path': '$.properties.revenue' }, items: [ { item_name: { '@path': `$.properties.products.0.name` }, item_id: { '@path': `$.properties.products.0.product_id` }, quantity: { '@path': `$.properties.products.0.quantity` }, coupon: { '@path': `$.properties.products.0.coupon` }, item_brand: { '@path': `$.properties.products.0.brand` }, item_category: { '@path': `$.properties.products.0.category` }, item_variant: { '@path': `$.properties.products.0.variant` }, price: { '@path': `$.properties.products.0.price` } } ] }, useDefaultMappings: false }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe('One of product name or product id is required for product or impression data.') } }) it('should handle default mappings', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Order Completed', userId: '3456fff', anonymousId: 'anon-567890', type: 'track', properties: { affiliation: 'TI Online Store', order_id: '5678dd9087-78', coupon: 'SUMMER_FEST', currency: 'EUR', products: [ { product_id: 'pid-123456', sku: 'SKU-123456', name: 'Tour t-shirt', quantity: 2, coupon: 'MOUNTAIN', brand: 'Canvas', category: 'T-Shirt', variant: 'Black', price: 19.98 } ], revenue: 5.99, shipping: 1.5, tax: 3.0, total: 24.48 } }) const responses = await testDestination.testAction('purchase', { event, settings: { apiSecret, measurementId }, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(201) expect(responses[0].request.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "content-type": Array [ "application/json", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.body).toMatchInlineSnapshot( `"{\\"client_id\\":\\"3456fff\\",\\"events\\":[{\\"name\\":\\"purchase\\",\\"params\\":{\\"affiliation\\":\\"TI Online Store\\",\\"coupon\\":\\"SUMMER_FEST\\",\\"currency\\":\\"EUR\\",\\"items\\":[],\\"transaction_id\\":\\"5678dd9087-78\\",\\"shipping\\":1.5,\\"value\\":24.48,\\"tax\\":3}}]}"` ) }) }) })
jbwyme/action-destinations
packages/browser-destinations/src/destinations/intercom/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * Your workspace ID (this appears as app _id in your code) is a unique code assigned to your app when you create it in Intercom. https://www.intercom.com/help/en/articles/3539-where-can-i-find-my-workspace-id-app-id */ app_id: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/index.ts
<gh_stars>0 import { defaultValues } from '@segment/actions-core' import createUpdateDevice from './createUpdateDevice' import createUpdatePerson from './createUpdatePerson' import trackEvent from './trackEvent' import triggerCampaign from './triggerCampaign' import type { DestinationDefinition } from '@segment/actions-core' import type { Settings } from './generated-types' const destination: DestinationDefinition<Settings> = { name: 'Customer.io', mode: 'cloud', authentication: { scheme: 'basic', fields: { siteId: { description: 'Customer.io site ID. This can be found on your [API Credentials page](https://fly.customer.io/settings/api_credentials).', // minLength: 20, label: 'Site ID', type: 'string', required: true }, apiKey: { description: 'Customer.io API key. This can be found on your [API Credentials page](https://fly.customer.io/settings/api_credentials).', // minLength: 20, label: 'API Key', type: 'string', required: true } }, testAuthentication: (request) => { return request('https://track.customer.io/auth') } }, extendRequest({ settings }) { return { username: settings.siteId, password: settings.apiKey } }, actions: { createUpdateDevice, createUpdatePerson, trackEvent, triggerCampaign }, presets: [ { name: 'Create or Update Person', subscribe: 'type = "identify"', partnerAction: 'createUpdatePerson', mapping: defaultValues(createUpdatePerson.fields) }, { name: 'Create or Update Device', subscribe: 'type = "track" and event = "Application Installed"', partnerAction: 'createUpdateDevice', mapping: defaultValues(createUpdateDevice.fields) }, { name: 'Track Event', subscribe: 'type = "track"', partnerAction: 'trackEvent', mapping: defaultValues(trackEvent.fields) } ] } export default destination
jbwyme/action-destinations
packages/cli/templates/actions/empty-browser-action/__tests__/index.test.ts
<gh_stars>0 import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import { destination } from '../../index' describe('{{destination}}.{{slug}}', () => { // TODO: Test your action })
jbwyme/action-destinations
packages/destination-actions/src/destinations/amplitude/index.ts
import type { DestinationDefinition } from '@segment/actions-core' import { defaultValues } from '@segment/actions-core' import identifyUser from './identifyUser' import logEvent from './logEvent' import mapUser from './mapUser' import groupIdentifyUser from './groupIdentifyUser' import type { Settings } from './generated-types' /** used in the quick setup */ const presets: DestinationDefinition['presets'] = [ { name: 'Track Calls', subscribe: 'type = "track"', partnerAction: 'logEvent', mapping: defaultValues(logEvent.fields) }, { name: 'Page Calls', subscribe: 'type = "page"', partnerAction: 'logEvent', mapping: { ...defaultValues(logEvent.fields), event_type: { '@template': 'Viewed {{name}}' } } }, { name: 'Screen Calls', subscribe: 'type = "screen"', partnerAction: 'logEvent', mapping: { ...defaultValues(logEvent.fields), event_type: { '@template': 'Viewed {{name}}' } } }, { name: 'Identify Calls', subscribe: 'type = "identify"', partnerAction: 'identifyUser', mapping: defaultValues(identifyUser.fields) }, { name: 'Browser Session Tracking', subscribe: 'type = "track" or type = "identify" or type = "group" or type = "page" or type = "alias"', partnerAction: 'sessionId', mapping: {} } ] const destination: DestinationDefinition<Settings> = { name: 'Amplitude (Actions)', mode: 'cloud', authentication: { scheme: 'custom', fields: { apiKey: { label: 'API Key', description: 'Amplitude project API key. You can find this key in the "General" tab of your Amplitude project.', type: 'string', required: true }, secretKey: { label: 'Secret Key', description: 'Amplitude project secret key. You can find this key in the "General" tab of your Amplitude project.', type: 'string', required: true } }, testAuthentication: (request, { settings }) => { // Note: Amplitude has some apis that use basic auth (like this one) // and others that use custom auth in the request body return request('https://amplitude.com/api/2/usersearch?user=<EMAIL>', { username: settings.apiKey, password: settings.secretKey }) } }, presets, actions: { logEvent, identifyUser, mapUser, groupIdentifyUser } } export default destination
jbwyme/action-destinations
packages/destination-actions/src/destinations/braze/trackPurchase/generated-types.ts
<filename>packages/destination-actions/src/destinations/braze/trackPurchase/generated-types.ts // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * The unique user identifier */ external_id?: string /** * A user alias object. See [the docs](https://www.braze.com/docs/api/objects_filters/user_alias_object/). */ user_alias?: { alias_name: string alias_label: string } /** * The unique user identifier */ braze_id?: string | null /** * When the event occurred. */ time: string | number /** * Products purchased */ products: { product_id: string currency?: string price: number quantity?: number }[] /** * Properties of the event */ properties?: { [k: string]: unknown } /** * Setting this flag to true will put the API in "Update Only" mode. When using a "user_alias", "Update Only" mode is always true. */ _update_existing_only?: boolean }
jbwyme/action-destinations
packages/core/src/get.ts
<reponame>jbwyme/action-destinations /** * Lightweight alternative to lodash.get with similar coverage * Supports basic path lookup via dot notation `'foo.bar[0].baz'` or an array ['foo', 'bar', '0', 'baz'] */ export function get<T = unknown, Default = undefined>( // eslint-disable-next-line @typescript-eslint/no-explicit-any obj: any, path: string | string[], defValue?: Default ): T | Default | undefined { // If path is not defined or it has false value if (!path) return defValue // Check if path is string or array. Regex : ensure that we do not have '.' and brackets. // Regex explained: https://regexr.com/58j0k const pathArray = Array.isArray(path) ? path : (path.match(/([^[.\]])+/g) as string[]) // Find value if exist return otherwise return undefined value const value = pathArray.reduce((prevObj, key) => prevObj && prevObj[key], obj) return typeof value !== 'undefined' ? value : defValue }
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/__tests__/login.test.ts
<filename>packages/destination-actions/src/destinations/google-analytics-4/__tests__/login.test.ts import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import ga4 from '../index' const testDestination = createTestIntegration(ga4) const apiSecret = '<KEY>' const measurementId = 'G-TESTTOKEN' describe('GA4', () => { describe('Signed In', () => { it('should handle a basic event', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Signed In', userId: 'abc123', type: 'track', properties: { login_method: 'Okta SSO' } }) const responses = await testDestination.testAction('login', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.userId' }, method: { '@path': '$.properties.login_method' } } }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(201) expect(responses[0].request.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "content-type": Array [ "application/json", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.body).toMatchInlineSnapshot( `"{\\"client_id\\":\\"abc123\\",\\"events\\":[{\\"name\\":\\"login\\",\\"params\\":{\\"method\\":\\"Okta SSO\\"}}]}"` ) }) }) })
jbwyme/action-destinations
packages/core/src/create-test-integration.ts
import { createTestEvent } from './create-test-event' import { Destination } from './destination-kit' import { mapValues } from './map-values' import type { DestinationDefinition } from './destination-kit' import type { JSONObject } from './json-object' import type { SegmentEvent } from './segment-event' import { AuthTokens } from './destination-kit/parse-settings' interface InputData<Settings> { /** * The Segment event. You can use `createTestEvent` if you want * to construct an event from partial data. */ event?: Partial<SegmentEvent> /** * The raw input - this is what customers define. It may include * literal values as well as mapping-kit directives. */ mapping?: JSONObject /** * The settings for a destination instance. Includes things like * `apiKey` or `subdomain`. Any fields that are used across all actions * in a destination. */ settings?: Settings /** * Whether or not to use default mappings in the test. * Set to `false` or omit if you want to explicitly provide the raw input. * Set to `true` if you want to test the defaultMappings (along with any mapping passed in) */ useDefaultMappings?: boolean auth?: AuthTokens } class TestDestination<T> extends Destination<T> { responses: Destination['responses'] = [] constructor(destination: DestinationDefinition<T>) { super(destination) } /** Testing method that runs an action e2e while allowing slightly more flexible inputs */ async testAction( action: string, { event, mapping, settings, useDefaultMappings, auth }: InputData<T> ): Promise<Destination['responses']> { mapping = mapping ?? {} if (useDefaultMappings) { const fields = this.definition.actions[action].fields const defaultMappings = mapValues(fields, 'default') mapping = { ...defaultMappings, ...mapping } as JSONObject } await super.executeAction(action, { event: createTestEvent(event), mapping, settings: settings ?? ({} as T), auth }) const responses = this.responses this.responses = [] return responses } } export function createTestIntegration<T>(destination: DestinationDefinition<T>): TestDestination<T> { return new TestDestination(destination) }
jbwyme/action-destinations
packages/core/src/__tests__/destination-kit.test.ts
import { Destination, DestinationDefinition } from '../destination-kit' import { JSONObject } from '../json-object' import { SegmentEvent } from '../segment-event' const destinationCustomAuth: DestinationDefinition<JSONObject> = { name: 'Google Analytics 4', mode: 'cloud', authentication: { scheme: 'custom', fields: { apiSecret: { label: 'API secret', description: 'Api key', type: 'string', required: true } } }, actions: { customEvent: { title: 'Send a Custom Event', description: 'Send events to a custom event in API', defaultSubscription: 'type = "track"', fields: {}, perform: (_request) => { return 'this is a test' } } } } const destinationOAuth2: DestinationDefinition<JSONObject> = { name: 'Google Analytics 4', mode: 'cloud', authentication: { scheme: 'oauth2', fields: { apiSecret: { label: 'API secret', description: 'Api key', type: 'string', required: true } }, refreshAccessToken: (_request) => { return new Promise((resolve, _reject) => { setTimeout(() => { resolve({ accessToken: 'fresh-token' }) }, 3) }) } }, actions: { customEvent: { title: 'Send a Custom Event', description: 'Send events to a custom event in API', defaultSubscription: 'type = "track"', fields: {}, perform: (_request) => { return 'this is a test' } } } } describe('destination kit', () => { describe('event validations', () => { test('should return `invalid subscription` when sending an empty subscribe', async () => { const destinationTest = new Destination(destinationCustomAuth) const testEvent: SegmentEvent = { type: 'track' } const testSettings = { subscription: { subscribe: '', partnerAction: 'customEvent' } } const res = await destinationTest.onEvent(testEvent, testSettings) expect(res).toEqual([{ output: 'invalid subscription' }]) }) test('should return invalid subscription with details when sending an invalid subscribe', async () => { const destinationTest = new Destination(destinationCustomAuth) const testEvent: SegmentEvent = { type: 'track' } const testSettings = { subscription: { subscribe: 'typo', partnerAction: 'customEvent' } } const res = await destinationTest.onEvent(testEvent, testSettings) expect(res).toEqual([{ output: "invalid subscription : Cannot read property 'type' of undefined" }]) }) test('should return `not subscribed` when providing an empty event', async () => { const destinationTest = new Destination(destinationCustomAuth) const testSettings = { subscription: { subscribe: 'type = "track"', partnerAction: 'customEvent' } } // @ts-ignore needed for replicating empty event at runtime const res = await destinationTest.onEvent({}, testSettings) expect(res).toEqual([{ output: 'not subscribed' }]) }) test('should succeed if provided with a valid event & settings', async () => { const destinationTest = new Destination(destinationCustomAuth) const testEvent: SegmentEvent = { properties: { field_one: 'test input' }, userId: '3456fff', type: 'track' } const testSettings = { apiSecret: 'test_key', subscription: { subscribe: 'type = "track"', partnerAction: 'customEvent', mapping: { clientId: '23455343467', name: 'fancy_event', parameters: { field_one: 'rogue one' } } } } const res = await destinationTest.onEvent(testEvent, testSettings) expect(res).toEqual([{ output: 'Mappings resolved' }, { output: 'this is a test' }]) }) test('should succeed when traits filtering is specified', async () => { const destinationTest = new Destination(destinationCustomAuth) const testEvent: SegmentEvent = { properties: { field_one: 'test input' }, traits: { a: 'foo' }, userId: '3456fff', type: 'identify' } const testSettings = { apiSecret: 'test_key', subscription: { subscribe: 'type = "identify" and traits.a = "foo"', partnerAction: 'customEvent', mapping: { clientId: '23455343467', name: 'fancy_event', parameters: { field_one: '<NAME>' } } } } const res = await destinationTest.onEvent(testEvent, testSettings) expect(res).toEqual([{ output: 'Mappings resolved' }, { output: 'this is a test' }]) }) test('should succeed when property filtering is specified', async () => { const destinationTest = new Destination(destinationCustomAuth) const testEvent: SegmentEvent = { properties: { field_one: 'test input' }, traits: { a: 'foo' }, userId: '3456fff', type: 'identify' } const testSettings = { apiSecret: 'test_key', subscription: { subscribe: 'type = "identify" and properties.a = "foo"', partnerAction: 'customEvent', mapping: { clientId: '23455343467', name: 'fancy_event', parameters: { field_one: '<NAME>' } } } } const res = await destinationTest.onEvent(testEvent, testSettings) expect(res).toEqual([{ output: 'Mappings resolved' }, { output: 'this is a test' }]) }) }) describe('refresh token', () => { test('should throw a `NotImplemented` error', async () => { const destinationTest = new Destination(destinationCustomAuth) const testSettings = { subscription: { subscribe: '', partnerAction: 'customEvent' } } const oauthData = { accessToken: 'test-access-token', refreshToken: '<PASSWORD>', clientId: 'test-clientid', clientSecret: 'test-clientsecret' } try { await destinationTest.refreshAccessToken(testSettings, oauthData) fail('test should have thrown a NotImplemented error') } catch (e) { expect(e.status).toEqual(501) expect(e.message).toEqual('refreshAccessToken is only valid with oauth2 authentication scheme') expect(e.code).toEqual('NotImplemented') } }) test('should throw a `NotImplemented` error', async () => { const destinationTest = new Destination(destinationOAuth2) const testSettings = { subscription: { subscribe: 'type = "track"', partnerAction: 'customEvent' } } const oauthData = { accessToken: 'test-access-token', refreshToken: '<PASSWORD>', clientId: 'test-clientid', clientSecret: 'test-clientsecret' } const res = await destinationTest.refreshAccessToken(testSettings, oauthData) expect(res).toEqual({ accessToken: 'fresh-token' }) }) }) })
jbwyme/action-destinations
packages/browser-destinations/src/destinations/intercom/show/index.ts
/* eslint-disable @typescript-eslint/no-unsafe-call */ import type { BrowserActionDefinition } from '../../../lib/browser-destinations' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: BrowserActionDefinition<Settings, Intercom_.IntercomStatic, Payload> = { title: 'Show', description: 'This will show the Messenger. If there are no new conversations, it will open to the Messenger Home. If there are, it will open with the message list.', platform: 'web', fields: {}, perform: (intercom) => { return intercom('show') } } export default action
jbwyme/action-destinations
packages/cli/src/lib/control-plane-client.ts
<gh_stars>0 import { controlPlaneService, DestinationMetadata, DestinationMetadataAction, DestinationMetadataActionCreateInput, DestinationMetadataActionsUpdateInput, DestinationMetadataUpdateInput, DestinationSubscriptionPresetInput, RemotePlugin } from '../lib/control-plane-service' const NOOP_CONTEXT = {} export async function getDestinationMetadatas(destinationIds: string[]): Promise<DestinationMetadata[]> { const { data, error } = await controlPlaneService.getAllDestinationMetadatas(NOOP_CONTEXT, { byIds: destinationIds }) if (error) { throw error } if (!data) { throw new Error('Could not load metadatas') } return data.metadatas } export async function getDestinationMetadataActions(destinationIds: string[]): Promise<DestinationMetadataAction[]> { const { data, error } = await controlPlaneService.getDestinationMetadataActions(NOOP_CONTEXT, { metadataIds: destinationIds }) if (error) { throw error } if (!data) { throw new Error('Could not load actions') } return data.actions } export async function updateDestinationMetadata( destinationId: string, input: DestinationMetadataUpdateInput ): Promise<DestinationMetadata> { const { data, error } = await controlPlaneService.updateDestinationMetadata(NOOP_CONTEXT, { destinationId, input }) if (error) { throw error } if (!data) { throw new Error('Could not update metadata') } return data.metadata } export async function setSubscriptionPresets(metadataId: string, presets: DestinationSubscriptionPresetInput[]) { const { data, error } = await controlPlaneService.setDestinationSubscriptionPresets(NOOP_CONTEXT, { metadataId, presets }) if (error) { console.log(error) throw error } if (!data) { throw new Error('Could not set subscription presets') } return data.presets } export async function createDestinationMetadataActions( input: DestinationMetadataActionCreateInput[] ): Promise<DestinationMetadataAction[]> { if (!input.length) return [] const { data, error } = await controlPlaneService.createDestinationMetadataActions(NOOP_CONTEXT, { input }) if (error) { console.log(error) throw error } if (!data) { throw new Error('Could not create metadata actions') } return data.actions } export async function updateDestinationMetadataActions( input: DestinationMetadataActionsUpdateInput[] ): Promise<DestinationMetadataAction[]> { if (!input.length) return [] const { data, error } = await controlPlaneService.updateDestinationMetadataActions(NOOP_CONTEXT, { input }) if (error) { throw error } if (!data) { throw new Error('Could not update metadata actions') } return data.actions } export async function getRemotePluginByDestinationIds(metadataIds: string[]): Promise<RemotePlugin[]> { const { data, error } = await controlPlaneService.getRemotePluginsByDestinationMetadataIds(NOOP_CONTEXT, { metadataIds }) if (error) { throw error } if (!data) { throw new Error('could not load remote plugins') } return data.remotePlugins } export async function updateRemotePlugin(plugin: RemotePlugin): Promise<RemotePlugin> { const { data, error } = await controlPlaneService.updateRemotePlugin(NOOP_CONTEXT, { metadataId: plugin.metadataId, name: plugin.name, input: { url: plugin.url, libraryName: plugin.libraryName } }) if (error) { throw error } if (!data) { throw new Error('could not update remote plugin') } return data.remotePlugin } export async function createRemotePlugin(plugin: RemotePlugin): Promise<RemotePlugin> { const { data, error } = await controlPlaneService.createRemotePlugin(NOOP_CONTEXT, { input: plugin }) if (error) { throw error } if (!data) { throw new Error('could not create remote plugin') } return data.remotePlugin }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/__tests__/initialization.test.ts
import appboy from '@braze/web-sdk' import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import brazeDestination from '../index' import { destination } from '../index' describe('initialization', () => { const settings = { safariWebsitePushId: 'safari', allowCrawlerActivity: true, doNotLoadFontAwesome: true, enableLogging: true, localization: 'pt', minimumIntervalBetweenTriggerActionsInSeconds: 60, openInAppMessagesInNewTab: true, sessionTimeoutInSeconds: 60, requireExplicitInAppMessageDismissal: true, enableHtmlInAppMessages: true, devicePropertyAllowlist: ['ay', 'Dios', 'mio'], devicePropertyWhitelist: ['foo', 'bar'], allowUserSuppliedJavascript: true, contentSecurityNonce: 'bar', endpoint: 'endpoint' } beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://segment.com' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) // we're not really testing that appboy loads here, so we'll just mock it out jest.spyOn(appboy, 'initialize').mockImplementation(() => true) jest.spyOn(appboy, 'openSession').mockImplementation(() => true) }) test('load initialization options', async () => { const initialize = jest.spyOn(appboy, 'initialize') const [trackEvent] = await brazeDestination({ api_key: 'b_123', subscriptions: [ { partnerAction: 'trackEvent', name: 'Log Custom Event', enabled: true, subscribe: 'type = "track"', mapping: { eventName: { '@path': '$.event' }, eventProperties: { '@path': '$.properties' } } } ], ...settings }) await trackEvent.load(Context.system(), {} as Analytics) const { endpoint, ...expectedSettings } = settings expect(initialize).toHaveBeenCalledWith( 'b_123', expect.objectContaining({ baseUrl: endpoint, ...expectedSettings }) ) }) test('loads sdk version 3.3 by default', async () => { const dependencies = { loadScript: jest.fn() } // @ts-expect-error await destination.initialize({ settings }, dependencies) expect(dependencies.loadScript).toHaveBeenCalledWith(`https://js.appboycdn.com/web-sdk/3.3/service-worker.js`) }) test('load different sdk versions', async () => { const withVersion = { ...settings, sdkVersion: '3.0' } const dependencies = { loadScript: jest.fn() } // @ts-expect-error await destination.initialize({ settings: withVersion }, dependencies) expect(dependencies.loadScript).toHaveBeenCalledWith( `https://js.appboycdn.com/web-sdk/${withVersion.sdkVersion}/service-worker.js` ) }) })
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/__tests__/integration.test.ts
<gh_stars>0 import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import braze, { destination } from '..' import type { Subscription } from '../../../lib/browser-destinations' const example: Subscription[] = [ { partnerAction: 'trackEvent', name: 'Log Custom Event', enabled: true, subscribe: 'type = "track"', mapping: { name: { '@path': '$.name' }, properties: { '@path': '$.properties' } } } ] beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://segment.com' }) const windowSpy = jest.spyOn(global, 'window', 'get') const documentSpy = jest.spyOn(global, 'document', 'get') windowSpy.mockImplementation(() => { return jsd.window as unknown as Window & typeof globalThis }) documentSpy.mockImplementation(() => jsd.window.document as unknown as Document) global.document.domain = 'segment.com' }) test('can load braze', async () => { const [trackEvent] = await braze({ api_key: 'api_key', endpoint: 'sdk.iad-01.braze.com', subscriptions: example }) jest.spyOn(destination.actions.trackEvent, 'perform') jest.spyOn(destination, 'initialize') await trackEvent.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() const ctx = await trackEvent.track?.( new Context({ type: 'track', properties: { banana: '📞' } }) ) expect(destination.actions.trackEvent.perform).toHaveBeenCalled() expect(ctx).not.toBeUndefined() }) test('loads the braze service worker', async () => { const [trackEvent] = await braze({ api_key: 'api_key', endpoint: 'sdk.iad-01.braze.com', subscriptions: example }) await trackEvent.load(Context.system(), {} as Analytics) const scripts = window.document.querySelectorAll('script') // loads the service worker expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://js.appboycdn.com/web-sdk/3.3/service-worker.js" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) }) describe('loads different versions of braze service worker', () => { test('3.0', async () => { const [trackEvent] = await braze({ api_key: 'api_key', endpoint: 'sdk.iad-01.braze.com', sdkVersion: '3.0', subscriptions: example }) await trackEvent.load(Context.system(), {} as Analytics) const scripts = window.document.querySelectorAll('script') // loads the service worker expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://js.appboycdn.com/web-sdk/3.0/service-worker.js" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) }) test('3.1', async () => { const [trackEvent] = await braze({ api_key: 'api_key', endpoint: 'sdk.iad-01.braze.com', sdkVersion: '3.1', subscriptions: example }) await trackEvent.load(Context.system(), {} as Analytics) const scripts = window.document.querySelectorAll('script') // loads the service worker expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://js.appboycdn.com/web-sdk/3.1/service-worker.js" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) }) test('3.2', async () => { const [trackEvent] = await braze({ api_key: 'api_key', endpoint: 'sdk.iad-01.braze.com', sdkVersion: '3.2', subscriptions: example }) await trackEvent.load(Context.system(), {} as Analytics) const scripts = window.document.querySelectorAll('script') // loads the service worker expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://js.appboycdn.com/web-sdk/3.2/service-worker.js" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) }) test('3.3', async () => { const [trackEvent] = await braze({ api_key: 'api_key', endpoint: 'sdk.iad-01.braze.com', sdkVersion: '3.3', subscriptions: example }) await trackEvent.load(Context.system(), {} as Analytics) const scripts = window.document.querySelectorAll('script') // loads the service worker expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://js.appboycdn.com/web-sdk/3.3/service-worker.js" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) }) })
jbwyme/action-destinations
packages/browser-destinations/src/destinations/fullstory/setUserVars/index.ts
<reponame>jbwyme/action-destinations<gh_stars>0 import type { BrowserActionDefinition } from '../../../lib/browser-destinations' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' import * as FullStory from '@fullstory/browser' // Change from unknown to the partner SDK types const action: BrowserActionDefinition<Settings, typeof FullStory, Payload> = { title: 'Set User Vars', description: 'Sets user identity variables', platform: 'web', defaultSubscription: "type = 'identify'", fields: { displayName: { type: 'string', required: false, description: "The user's display name", label: 'displayName' }, email: { type: 'string', required: false, description: "The user's email", label: 'email' }, traits: { type: 'object', required: false, description: 'The Segment traits to be forwarded to FullStory', label: 'traits' } }, perform: (client, event) => { client.setUserVars({ ...event.payload.traits, email: event.payload.email, displayName: event.payload.displayName }) } } export default action
jbwyme/action-destinations
packages/core/src/destination-kit/fields-to-jsonschema.ts
import { JSONSchema4, JSONSchema4Type, JSONSchema4TypeName } from 'json-schema' import type { InputField, GlobalSetting, FieldTypeName, Optional } from './types' function toJsonSchemaType(type: FieldTypeName): JSONSchema4TypeName | JSONSchema4TypeName[] { switch (type) { case 'string': case 'text': case 'password': return 'string' case 'datetime': return ['string', 'number'] default: return type } } export type MinimalInputField = Optional<InputField, 'description'> | Optional<GlobalSetting, 'description'> export type MinimalFields = Record<string, MinimalInputField> interface SchemaOptions { tsType?: boolean } export function fieldsToJsonSchema(fields: MinimalFields = {}, options?: SchemaOptions): JSONSchema4 { const required: string[] = [] const properties: Record<string, JSONSchema4> = {} for (const [key, field] of Object.entries(fields)) { const schemaType = toJsonSchemaType(field.type) let schema: JSONSchema4 = { title: field.label, description: field.description, type: schemaType, format: field.format, default: field.default as JSONSchema4Type } if (field.type === 'datetime') { schema.format = 'date-like' if (options?.tsType) { // Override generated types schema.tsType = 'string | number' } } else if (field.type === 'password') { schema.format = 'password' } else if (field.type === 'text') { schema.format = 'text' } if ('allowNull' in field && field.allowNull) { schema.type = ([] as JSONSchema4TypeName[]).concat(schemaType, 'null') if (typeof schema.tsType === 'string' && !schema.tsType.includes('null')) { schema.tsType += ' | null' } } const isMulti = 'multiple' in field && field.multiple if (isMulti) { schema.items = { type: schemaType } schema.type = 'array' } if (schemaType === 'object' && field.properties) { if (isMulti) { schema.items = fieldsToJsonSchema(field.properties) } else { schema = { ...schema, ...fieldsToJsonSchema(field.properties) } } } properties[key] = schema // Grab all the field keys with `required: true` if (field.required) { required.push(key) } } return { $schema: 'http://json-schema.org/schema#', type: 'object', additionalProperties: false, properties, required } }
jbwyme/action-destinations
packages/core/src/schema-validation.ts
<reponame>jbwyme/action-destinations // @ts-ignore no types import { AggregateAjvError } from '@segment/ajv-human-errors' import Ajv from 'ajv' import dayjs from 'dayjs' const ajv = new Ajv({ // Coerce types to be a bit more liberal. coerceTypes: true, // Return all validation errors, not just the first. allErrors: true, // Include reference to schema and data in error values. verbose: true, // Remove properties not defined the schema object removeAdditional: true, // Use a more parse-able format for JSON paths. jsonPointers: true }) // Extend with additional supported formats for action `fields` ajv.addFormat('password', () => true) ajv.addFormat('text', () => true) ajv.addFormat('date-like', (data: string) => { let date = dayjs(data) if (String(Number(data)) === data) { // parse as unix if (data.length === 13) { date = dayjs(Number(data)) } date = dayjs.unix(Number(data)) } return date.isValid() }) /** * Validates an object against a json schema * and caches the schema for subsequent validations when a key is provided */ export function validateSchema(obj: unknown, schema: object, schemaKey?: string) { let validate: Ajv.ValidateFunction if (schemaKey) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion validate = ajv.getSchema(schemaKey) || ajv.addSchema(schema, schemaKey).getSchema(schemaKey)! } else { validate = ajv.compile(schema) } if (!validate(obj)) { // eslint-disable-next-line @typescript-eslint/no-unsafe-call throw new AggregateAjvError(validate.errors) } }
jbwyme/action-destinations
packages/cli/src/commands/push-browser-destinations.ts
<reponame>jbwyme/action-destinations import { Command, flags } from '@oclif/command' import execa from 'execa' import chalk from 'chalk' import { manifest } from '@segment/browser-destinations' import ora from 'ora' import { assetPath } from '../config' import type { RemotePlugin } from '../lib/control-plane-service' import { prompt } from '../lib/prompt' import { getDestinationMetadatas, getRemotePluginByDestinationIds, createRemotePlugin, updateRemotePlugin } from '../lib/control-plane-client' export default class PushBrowserDestinations extends Command { private spinner: ora.Ora = ora() static description = `Builds and uploads browser destinations to Segment's database and s3 instance. Requires \`robo stage.ssh\` or \`robo prod.ssh\` and platform-write access.` static examples = [`$ ./bin/run push-browser-destinations`] static flags = { help: flags.help({ char: 'h' }), env: flags.string({ char: 'e', default: 'stage', env: 'NODE_ENV' }) } static args = [] async run() { const { flags } = this.parse(PushBrowserDestinations) const { destinationIds } = await prompt<{ destinationIds: string[] }>({ type: 'multiselect', name: 'destinationIds', message: 'Browser Destinations:', choices: Object.entries(manifest).map(([id, entry]) => ({ title: entry.definition.name, value: id })) }) const path = assetPath(flags.env) if (!destinationIds.length) { this.warn(`You must select at least one destination. Exiting...`) this.exit() } this.spinner.start( `Fetching existing definitions for ${destinationIds .map((id) => chalk.greenBright(manifest[id].definition.name)) .join(', ')}...` ) const metadatas = await getDestinationMetadatas(destinationIds) this.spinner.stop() const notFound = destinationIds.filter((destId) => !metadatas.map((m) => m.id).includes(destId)) if (notFound.length) { this.log(`Could not find destination definitions for ${notFound.map((id) => manifest[id].definition.name)}.`) } const remotePlugins: RemotePlugin[] = await getRemotePluginByDestinationIds(destinationIds) try { this.spinner.start(`Building libraries`) await build(flags.env) } catch (e) { this.error(e) } finally { this.spinner.stop() } for (const metadata of metadatas) { this.spinner.start(`Saving remote plugin for ${metadata.name}`) const entry = manifest[metadata.id] const input = { metadataId: metadata.id, name: metadata.name, // This MUST match the way webpack exports the libraryName in the umd bundle // TODO make this more automatic for consistency libraryName: `${entry.directory}Destination`, url: `${path}/${entry.directory}.js` } // We expect that each definition produces a single Remote Plugin bundle // `name` + `metadataId` are guaranteed to be unique const existingPlugin = remotePlugins.find((p) => p.metadataId === metadata.id && p.name === metadata.name) if (existingPlugin) { await updateRemotePlugin(input) this.spinner.succeed(`Updated existing remote plugin for ${metadata.name}`) } else { await createRemotePlugin(input) this.spinner.succeed(`Created new remote plugin for ${metadata.name}`) } } try { this.spinner.start(`Syncing all plugins to s3`) await syncToS3(flags.env) this.spinner.stop() this.log(`Plugins synced to s3`) } catch (e) { this.spinner.stop() this.error(e) } } } async function build(env: string): Promise<string> { execa.commandSync('lerna run build') if (env === 'production') { return execa.commandSync('lerna run build-web').stdout } return execa.commandSync('lerna run build-web-stage').stdout } async function syncToS3(env: string): Promise<string> { if (env === 'production') { return execa.commandSync(`lerna run deploy-prod`).stdout } return execa.commandSync(`lerna run deploy-stage`).stdout }
jbwyme/action-destinations
packages/destination-actions/src/destinations/amplitude/mapUser/index.ts
import { URLSearchParams } from 'url' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Map User', description: 'Merge two users together that would otherwise have different User IDs tracked in Amplitude.', defaultSubscription: 'type = "alias"', fields: { user_id: { label: 'User ID', type: 'string', description: 'The User ID to be associated', default: { '@path': '$.previousId' } }, global_user_id: { label: 'Global User ID', type: 'string', description: 'The global User ID to associate to', default: { '@path': '$.userId' } }, min_id_length: { label: 'Minimum ID Length', description: 'Amplitude has a default minimum id lenght of 5 characters for user_id and device_id fields. This field allows the minimum to be overridden to allow shorter id lengths.', allowNull: true, type: 'integer' } }, perform: (request, { payload, settings }) => { const { min_id_length } = payload const options = min_id_length && min_id_length > 0 ? JSON.stringify({ min_id_length }) : undefined return request('https://api.amplitude.com/usermap', { method: 'post', body: new URLSearchParams({ api_key: settings.apiKey, mapping: JSON.stringify([payload]), ...(options && { options }) }) }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/braze/updateUserProfile/index.ts
<reponame>jbwyme/action-destinations<gh_stars>0 import { omit, removeUndefined, IntegrationError } from '@segment/actions-core' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' import dayjs from '../../../lib/dayjs' type DateInput = string | Date | number | null | undefined type DateOutput = string | undefined | null function toISO8601(date: DateInput): DateOutput { if (date === null || date === undefined) { return date } const d = dayjs(date) return d.isValid() ? d.toISOString() : undefined } function toDateFormat(date: DateInput, format: string): DateOutput { if (date === null || date === undefined) { return date } const d = dayjs(date) return d.isValid() ? d.format(format) : undefined } function removeEmpty(obj: unknown) { if (!obj) { return obj } const cleaned = removeUndefined(obj) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (typeof cleaned === 'object' && Object.keys(cleaned!).length > 0) { return cleaned } return undefined } function toBrazeGender(gender: string | null | undefined): string | null | undefined { if (!gender) { return gender } const genders: Record<string, string[]> = { M: ['man', 'male', 'm'], F: ['woman', 'female', 'w', 'f'], O: ['other', 'o'], N: ['not applicable', 'n'], P: ['prefer not to say', 'p'] } const brazeGender = Object.keys(genders).find((key) => genders[key].includes(gender.toLowerCase())) return brazeGender || gender } const action: ActionDefinition<Settings, Payload> = { title: 'Update User Profile', description: "Update a user's profile attributes in Braze", defaultSubscription: 'type = "identify"', fields: { external_id: { label: 'External User ID', description: 'The unique user identifier', type: 'string', default: { '@path': '$.userId' } }, user_alias: { label: 'User Alias Object', description: 'A user alias object. See [the docs](https://www.braze.com/docs/api/objects_filters/user_alias_object/).', type: 'object', properties: { alias_name: { label: 'Alias Name', type: 'string', required: true }, alias_label: { label: 'Alias Label', type: 'string', required: true } } }, braze_id: { label: 'Braze User Identifier', description: 'The unique user identifier', type: 'string', allowNull: true, default: { '@path': '$.properties.braze_id' } }, country: { label: 'Country', description: 'The country code of the user', type: 'string', allowNull: true, default: { '@path': '$.context.location.country' } }, current_location: { label: 'Current Location', description: "The user's current longitude/latitude.", type: 'object', allowNull: true, properties: { latitude: { label: 'Latitude', type: 'number' }, longitude: { label: 'Longitude', type: 'number' } }, default: { latitude: { '@path': '$.context.location.latitude' }, longitude: { '@path': '$.context.location.longitude' } } }, date_of_first_session: { label: 'Date of First Session', description: 'The date the user first used the app', type: 'datetime', allowNull: true }, date_of_last_session: { label: 'Date of Last Session', description: 'The date the user last used the app', type: 'datetime', allowNull: true }, dob: { label: 'Date of Birth', description: "The user's date of birth", type: 'datetime', allowNull: true }, email: { label: 'Email', description: "The user's email", type: 'string', format: 'email', allowNull: true, default: { '@path': '$.traits.email' } }, email_subscribe: { label: 'Email Subscribe', description: `The user's email subscription preference: “opted_in” (explicitly registered to receive email messages), “unsubscribed” (explicitly opted out of email messages), and “subscribed” (neither opted in nor out).`, type: 'string' }, email_open_tracking_disabled: { label: 'Email Open Tracking Disabled', description: 'Set to true to disable the open tracking pixel from being added to all future emails sent to this user.', type: 'boolean' }, email_click_tracking_disabled: { label: 'Email Click Tracking Disabled', description: 'Set to true to disable the click tracking for all links within a future email, sent to this user.', type: 'boolean' }, facebook: { label: 'Facebook Attribution Data', description: 'Hash of Facebook attribution containing any of `id` (string), `likes` (array of strings), `num_friends` (integer).', type: 'object', properties: { id: { label: 'Facebook ID', type: 'string' }, likes: { label: 'Facebook Likes', type: 'string', multiple: true }, num_friends: { label: 'Facebook Number of Friends', type: 'integer' } } }, first_name: { label: '<NAME>', description: `The user's first name`, type: 'string', allowNull: true, default: { '@path': '$.traits.firstName' } }, gender: { label: 'Gender', description: "The user's gender: “M”, “F”, “O” (other), “N” (not applicable), “P” (prefer not to say) or nil (unknown).", type: 'string', allowNull: true, default: { '@path': '$.traits.gender' } }, home_city: { label: 'Home City', description: "The user's home city.", type: 'string', allowNull: true, default: { '@path': '$.traits.address.city' } }, image_url: { label: 'Image URL', description: 'URL of image to be associated with user profile.', type: 'string', format: 'uri', allowNull: true, default: { '@path': '$.traits.avatar' } }, language: { label: 'Language', description: "The user's preferred language.", type: 'string', allowNull: true }, last_name: { label: 'Last Name', description: "The user's last name", type: 'string', default: { '@path': '$.traits.lastName' } }, marked_email_as_spam_at: { label: 'Marked Email as Spam At', description: 'The date the user marked their email as spam.', type: 'datetime', allowNull: true }, phone: { label: 'Phone Number', description: "The user's phone number", type: 'string', allowNull: true, default: { '@path': '$.traits.phone' } }, push_subscribe: { label: 'Push Subscribe', description: `The user's push subscription preference: “opted_in” (explicitly registered to receive push messages), “unsubscribed” (explicitly opted out of push messages), and “subscribed” (neither opted in nor out).`, type: 'string' }, push_tokens: { label: 'Push Tokens', description: 'Array of objects with app_id and token string. You may optionally provide a device_id for the device this token is associated with, e.g., [{"app_id": App Identifier, "token": "abcd", "device_id": "optional_field_value"}]. If a device_id is not provided, one will be randomly generated.', type: 'object', multiple: true, properties: { app_id: { label: 'App ID', description: 'The app identifier for the push token.', type: 'string', required: true }, token: { label: 'Token', description: 'The push token.', type: 'string', required: true }, device_id: { label: 'Device ID', description: 'Identifier for the device associated with this token', type: 'string' } } }, time_zone: { label: 'Time zone', description: 'The user’s time zone name from IANA Time Zone Database (e.g., “America/New_York” or “Eastern Time (US & Canada)”). Only valid time zone values will be set.', type: 'string' }, twitter: { label: 'Twitter Attribution Data', description: 'Hash containing any of id (integer), screen_name (string, Twitter handle), followers_count (integer), friends_count (integer), statuses_count (integer).', type: 'object', properties: { id: { label: 'Twitter ID', type: 'string' }, screen_name: { label: '<NAME>', type: 'string' }, followers_count: { label: 'Number of Followers', type: 'integer' }, friends_count: { label: 'Number of Friends', type: 'integer' }, statuses_count: { label: 'Number of Statuses', type: 'integer' } } }, custom_attributes: { label: 'Custom Attributes', description: 'Hash of custom attributes to send to Braze', type: 'object', default: { '@path': '$.traits' } }, _update_existing_only: { label: 'Update Existing Only', description: 'Setting this flag to true will put the API in "Update Only" mode. When using a "user_alias", "Update Only" mode is always true.', type: 'boolean', default: false } }, perform: (request, { settings, payload }) => { const { braze_id, user_alias, external_id } = payload if (!braze_id && !user_alias && !external_id) { throw new IntegrationError( 'One of "external_id" or "user_alias" or "braze_id" is required.', 'Missing required fields', 400 ) } // Since we are merge reserved keys on top of custom_attributes we need to remove them // to respect the customers mappings that might resolve `undefined`, without this we'd // potentially send a value from `custom_attributes` that conflicts with their mappings. const reservedKeys = Object.keys(action.fields) const customAttrs = omit(payload.custom_attributes, reservedKeys) return request(`${settings.endpoint}/users/track`, { method: 'post', json: { attributes: [ { ...customAttrs, braze_id, external_id, user_alias, // TODO format country code according to ISO-3166-1 alpha-2 standard? // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 country: payload.country, current_location: removeEmpty(payload.current_location), date_of_first_session: toISO8601(payload.date_of_first_session), date_of_last_session: toISO8601(payload.date_of_last_session), dob: toDateFormat(payload.dob, 'YYYY-MM-DD'), email: payload.email, email_subscribe: payload.email_subscribe, email_open_tracking_disabled: payload.email_open_tracking_disabled, email_click_tracking_disabled: payload.email_click_tracking_disabled, facebook: payload.facebook, first_name: payload.first_name, gender: toBrazeGender(payload.gender), home_city: payload.home_city, image_url: payload.image_url, // TODO format as ISO-639-1 standard ? // https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes // https://www.braze.com/docs/user_guide/data_and_analytics/user_data_collection/language_codes/ language: payload.language, last_name: payload.last_name, marked_email_as_spam_at: toISO8601(payload.marked_email_as_spam_at), phone: payload.phone, push_subscribe: payload.push_subscribe, push_tokens: payload.push_tokens, time_zone: payload.time_zone, twitter: payload.twitter, _update_existing_only: payload._update_existing_only } ] } }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-enhanced-conversions/postConversion/formatter.ts
<filename>packages/destination-actions/src/destinations/google-enhanced-conversions/postConversion/formatter.ts import { createHash } from 'crypto' /** * Acceptable data types for k:v pairs. */ type DataValues = Record<string, string | string[] | number | undefined> /** * Removes all k:v pairs where the value is falsy. */ export function cleanData(data: DataValues): { [key: string]: unknown } { if (data == null) { return {} } const obj: { [key: string]: unknown } = {} for (const key in data) { const value = data[key] if (Array.isArray(value)) { // remove empty entries const filtered = value.filter((item) => item) if (filtered.length !== 0) { obj[key] = filtered } } else if (value) { obj[key] = value } } return obj } /** * Convert emails to lower case, remove all spaces, and remove all "." before the "@". */ export function formatEmail(email: string): string { let formattedEmail if (email.toLowerCase().search('@gmail') > -1 || email.toLowerCase().search('@googlemail.com') > -1) { // remove all spaces + lower case output formattedEmail = email.toLowerCase().replace(/ /g, '') // remove all periods before the "@" const name = formattedEmail.substr(0, formattedEmail.indexOf('@')).replace(/\./g, '') const domain = formattedEmail.substr(formattedEmail.indexOf('@'), formattedEmail.length) return hashAndEncode(name.concat(domain)) } else { return hashAndEncode(email.toLowerCase().replace(/ /g, '')) } } /** * Convert string to match E.164 phone number pattern (e.g. +1234567890) * Note it is up to the advertiser to pass only valid phone numbers and formats. * This function assumes the input is a correctly formatted phone number maximum of 14 characters long with country code included in the input. */ export function formatPhone(phone?: string): string { if (!phone) return '' const validatedPhone = phone.match(/[0-9]{0,14}/g) if (validatedPhone === null) { throw new Error(`${phone} is not a valid E.164 phone number.`) } // Remove spaces and non-digits; append + to the beginning let formattedPhone = `+${phone.replace(/[^0-9]/g, '')}` // Limit length to 15 characters formattedPhone = formattedPhone.substring(0, 15) return hashAndEncode(formattedPhone) } export function formatFirstName(firstName?: string): string { if (!firstName) return '' return hashAndEncode(firstName.toLowerCase().replace(/[^a-z]/g, '')) } export function formatLastName(lastName?: string): string { if (!lastName) return '' return hashAndEncode(lastName.toLowerCase().replace(/[^a-z]/g, '')) } export function formatStreet(street?: string): string { if (!street) return '' return hashAndEncode(street.toLowerCase()) } export function formatCity(city?: string): string { if (!city) return '' return city.toLowerCase().replace(/[^a-z]/g, '') } export function formatRegion(region?: string): string { if (!region) return '' return region.toLowerCase().replace(/[^a-z]/g, '') } function hashAndEncode(property: string) { return createHash('sha256').update(property).digest('base64') }
jbwyme/action-destinations
packages/destination-actions/src/destinations/amplitude/identifyUser/index.ts
<filename>packages/destination-actions/src/destinations/amplitude/identifyUser/index.ts import { URLSearchParams } from 'url' import { ActionDefinition, omit, removeUndefined } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' import { convertUTMProperties } from '../utm' import { convertReferrerProperty } from '../referrer' import { parseUserAgentProperties } from '../user-agent' import { mergeUserProperties } from '../merge-user-properties' import { AmplitudeEvent } from '../logEvent' const action: ActionDefinition<Settings, Payload> = { title: 'Identify User', description: 'Set the user ID for a particular device ID or update user properties without sending an event to Amplitude.', defaultSubscription: 'type = "identify"', fields: { user_id: { label: 'User ID', type: 'string', allowNull: true, description: 'A UUID (unique user ID) specified by you. **Note:** If you send a request with a user ID that is not in the Amplitude system yet, then the user tied to that ID will not be marked new until their first event. Required unless device ID is present.', default: { '@path': '$.userId' } }, device_id: { label: 'Device ID', type: 'string', description: 'A device specific identifier, such as the Identifier for Vendor (IDFV) on iOS. Required unless user ID is present.', default: { '@if': { exists: { '@path': '$.context.device.id' }, then: { '@path': '$.context.device.id' }, else: { '@path': '$.anonymousId' } } } }, user_properties: { label: 'User Properties', type: 'object', description: 'Additional data tied to the user in Amplitude. Each distinct value will show up as a user segment on the Amplitude dashboard. Object depth may not exceed 40 layers. **Note:** You can store property values in an array and date values are transformed into string values.', default: { '@path': '$.traits' } }, groups: { label: 'Groups', type: 'object', description: "Groups of users for Amplitude's account-level reporting feature. Note: You can only track up to 5 groups. Any groups past that threshold will not be tracked. **Note:** This feature is only available to Amplitude Enterprise customers who have purchased the Amplitude Accounts add-on." }, app_version: { label: 'App Version', type: 'string', description: 'Version of the app the user is on.', default: { '@path': '$.context.app.version' } }, platform: { label: 'Platform', type: 'string', description: 'What platform is sending the data.', default: { '@path': '$.context.device.type' } }, os_name: { label: 'OS Name', type: 'string', description: 'Mobile operating system or browser the user is on.', default: { '@path': '$.context.os.name' } }, os_version: { label: 'OS Version', type: 'string', description: 'Version of the mobile operating system or browser the user is on.', default: { '@path': '$.context.os.version' } }, device_brand: { label: 'Device Brand', type: 'string', description: 'Device brand the user is on.', default: { '@path': '$.context.device.brand' } }, device_manufacturer: { label: 'Device Manufacturer', type: 'string', description: 'Device manufacturer the user is on.', default: { '@path': '$.context.device.manufacturer' } }, device_model: { label: 'Device Model', type: 'string', description: 'Device model the user is on.', default: { '@path': '$.context.device.model' } }, carrier: { label: 'Carrier', type: 'string', description: 'Carrier the user has.', default: { '@path': '$.context.network.carrier' } }, country: { label: 'Country', type: 'string', description: 'Country the user is in.', default: { '@path': '$.context.location.country' } }, region: { label: 'Region', type: 'string', description: 'Geographical region the user is in.', default: { '@path': '$.context.location.region' } }, city: { label: 'City', type: 'string', description: 'What city the user is in.', default: { '@path': '$.context.location.city' } }, dma: { label: 'Designated Market Area', type: 'string', description: 'The Designated Market Area of the user.' }, language: { label: 'Language', type: 'string', description: 'Language the user has set.', default: { '@path': '$.context.locale' } }, paying: { label: 'Is Paying', type: 'boolean', description: 'Whether the user is paying or not.' }, start_version: { label: 'Initial Version', type: 'string', description: 'Version of the app the user was first on.' }, insert_id: { label: 'Insert ID', type: 'string', description: 'Amplitude will deduplicate subsequent events sent with this ID we have already seen before within the past 7 days. Amplitude recommends generating a UUID or using some combination of device ID, user ID, event type, event ID, and time.' }, userAgent: { label: 'User Agent', type: 'string', description: 'The user agent of the device sending the event.', default: { '@path': '$.context.user_agent' } }, userAgentParsing: { label: 'User Agent Parsing', type: 'boolean', description: 'Enabling this setting will set the Device manufacturer, Device Model and OS Name properties based on the user agent string provided in the userAgent field', default: true }, utm_properties: { label: 'UTM Properties', type: 'object', description: 'UTM Tracking Properties', properties: { utm_source: { label: 'UTM Source', type: 'string' }, utm_medium: { label: 'UTM Medium', type: 'string' }, utm_campaign: { label: 'UTM Campaign', type: 'string' }, utm_term: { label: 'UTM Term', type: 'string' }, utm_content: { label: 'UTM Content', type: 'string' } }, default: { utm_source: { '@path': '$.context.campaign.source' }, utm_medium: { '@path': '$.context.campaign.medium' }, utm_campaign: { '@path': '$.context.campaign.name' }, utm_term: { '@path': '$.context.campaign.term' }, utm_content: { '@path': '$.context.campaign.content' } } }, referrer: { label: 'Referrer', type: 'string', description: 'The referrer of the web request. Sent to Amplitude as both last touch “referrer” and first touch “initial_referrer”', default: { '@path': '$.context.page.referrer' } }, min_id_length: { label: 'Minimum ID Length', description: 'Amplitude has a default minimum id lenght of 5 characters for user_id and device_id fields. This field allows the minimum to be overridden to allow shorter id lengths.', allowNull: true, type: 'integer' } }, perform: (request, { payload, settings }) => { const { utm_properties, referrer, userAgent, userAgentParsing, min_id_length, ...rest } = payload let options const properties = rest as AmplitudeEvent if (Object.keys(utm_properties ?? {}).length || referrer) { properties.user_properties = mergeUserProperties( omit(properties.user_properties ?? {}, ['utm_properties', 'referrer']), convertUTMProperties(payload), convertReferrerProperty(payload) ) } if (min_id_length && min_id_length > 0) { options = JSON.stringify({ min_id_length }) } const identification = JSON.stringify({ // Conditionally parse user agent using amplitude's library ...(userAgentParsing && parseUserAgentProperties(userAgent)), // Make sure any top-level properties take precedence over user-agent properties ...removeUndefined(properties), library: 'segment' }) return request('https://api.amplitude.com/identify', { method: 'post', body: new URLSearchParams({ api_key: settings.apiKey, identification, options }) }) } } export default action
jbwyme/action-destinations
packages/browser-destinations/src/destinations/amplitude-plugins/sessionId/__tests__/sessionId.test.ts
<gh_stars>0 import { Analytics, Context, Plugin } from '@segment/analytics-next' import * as jsdom from 'jsdom' import browserPluginsDestination from '../..' import { Subscription } from '../../../../lib/browser-destinations' expect.extend({ toBeWithinOneSecondOf(got, expected) { if (typeof got === 'string') { got = parseInt(got, 10) } if (typeof expected === 'string') { got = parseInt(expected, 10) } const oneSecond = 1000 const timeDiff = Math.abs(expected - got) const timeDiffInSeconds = timeDiff / 1000 const pass = timeDiff < oneSecond const message = () => `${got} should be within a second of ${expected}, ` + `actual difference: ${timeDiffInSeconds.toFixed(1)}s` return { pass, message } } }) const example: Subscription[] = [ { partnerAction: 'sessionId', name: 'SessionId', enabled: true, subscribe: 'type = "track"', mapping: {} } ] let browserActions: Plugin[] let sessionIdPlugin: Plugin let ajs: Analytics beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://localhost' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) browserActions = await browserPluginsDestination({ subscriptions: example }) sessionIdPlugin = browserActions[0] ajs = new Analytics({ writeKey: 'w_123' }) }) describe('ajs-integration', () => { test('updates the original event with a session id', async () => { await sessionIdPlugin.load(Context.system(), ajs) const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) const updatedCtx = await sessionIdPlugin.track?.(ctx) // @ts-expect-error Need to fix ajs-next types to allow for complex objects in `integrations` expect(updatedCtx?.event.integrations?.Amplitude?.session_id).not.toBeUndefined() }) test('runs as an enrichment middleware', async () => { await ajs.register(sessionIdPlugin) jest.spyOn(sessionIdPlugin, 'track') const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) await ajs.track(ctx.event) expect(sessionIdPlugin.track).toHaveBeenCalled() expect(ajs.queue.plugins.map((p) => ({ name: p.name, type: p.type }))).toMatchInlineSnapshot(` Array [ Object { "name": "Amplitude (Actions) sessionId", "type": "enrichment", }, ] `) }) }) describe('sessoinId', () => { beforeEach(async () => { jest.useFakeTimers() await sessionIdPlugin.load(Context.system(), ajs) }) const id = () => new Date().getTime() describe('new sessions', () => { test('sets a session id', async () => { const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) const updatedCtx = await sessionIdPlugin.track?.(ctx) // @ts-expect-error Need to fix ajs-next types to allow for complex objects in `integrations` expect(updatedCtx?.event.integrations?.Amplitude?.session_id).toBeWithinOneSecondOf(id()) }) test('persists the session id', async () => { const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) await sessionIdPlugin.track?.(ctx) expect(window.localStorage.getItem('analytics_session_id')).toBeWithinOneSecondOf(id().toString()) expect(window.localStorage.getItem('analytics_session_id.last_access')).toBeWithinOneSecondOf(id().toString()) }) }) describe('existing sessions', () => { test('uses an existing session id', async () => { const then = id() jest.advanceTimersByTime(10000) window.localStorage.setItem('analytics_session_id', then.toString()) const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) const updatedCtx = await sessionIdPlugin.track?.(ctx) // @ts-expect-error Need to fix ajs-next types to allow for complex objects in `integrations` expect(updatedCtx?.event.integrations?.Amplitude?.session_id).toBeWithinOneSecondOf(then) }) test('keeps track of when the session was last accessed', async () => { const then = id() jest.advanceTimersByTime(10000) window.localStorage.setItem('analytics_session_id', then.toString()) const now = id() const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) const updatedCtx = await sessionIdPlugin.track?.(ctx) // @ts-expect-error Need to fix ajs-next types to allow for complex objects in `integrations` expect(updatedCtx?.event.integrations?.Amplitude?.session_id).toBeWithinOneSecondOf(then) expect(window.localStorage.getItem('analytics_session_id.last_access')).toBeWithinOneSecondOf(now) }) test('reset session when stale', async () => { const then = id() window.localStorage.setItem('analytics_session_id.last_access', then.toString()) window.localStorage.setItem('analytics_session_id', then.toString()) const THIRTY_MINUTES = 30 * 60000 jest.advanceTimersByTime(THIRTY_MINUTES) const now = id() const ctx = new Context({ type: 'track', event: 'greet', properties: { greeting: 'Oi!' } }) const updatedCtx = await sessionIdPlugin.track?.(ctx) // @ts-expect-error Need to fix ajs-next types to allow for complex objects in `integrations` expect(updatedCtx?.event.integrations?.Amplitude?.session_id).toBeWithinOneSecondOf(now) expect(window.localStorage.getItem('analytics_session_id')).toBeWithinOneSecondOf(now.toString()) expect(window.localStorage.getItem('analytics_session_id.last_access')).toBeWithinOneSecondOf(now.toString()) }) }) })
jbwyme/action-destinations
packages/destination-actions/src/destinations/slack/postToChannel/generated-types.ts
<gh_stars>0 // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * Slack webhook URL. */ url: string /** * The text message to post to Slack. You can use [Slack's formatting syntax.](https://api.slack.com/reference/surfaces/formatting) */ text: string /** * Slack channel to post message to. */ channel?: string /** * User name to post messages as. */ username?: string /** * URL for user icon image. */ icon_url?: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/customEvent/generated-types.ts
<reponame>jbwyme/action-destinations // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * Uniquely identifies a user instance of a web client. */ clientId: string /** * The unique name of the custom event created in GA4. */ name: string /** * The event parameters to send to Google */ params?: { [k: string]: unknown } }
jbwyme/action-destinations
packages/destination-actions/src/destinations/twilio/sendSms/index.ts
<reponame>jbwyme/action-destinations<filename>packages/destination-actions/src/destinations/twilio/sendSms/index.ts import { URLSearchParams } from 'url' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Send SMS', description: 'Sends an SMS message', defaultSubscription: 'type = "track"', fields: { To: { label: 'To', description: 'The Phone Number to send a SMS to', type: 'string', required: true }, Body: { label: 'Body', description: 'The message body', type: 'text', required: true } }, perform: (request, data) => { return request(`https://api.twilio.com/2010-04-01/Accounts/${data.settings.accountId}/Messages.json`, { method: 'post', // Fetch will automatically set the content-type for this `body` // to application/x-www-form-urlencoded;charset=UTF-8 body: new URLSearchParams({ From: data.settings.phoneNumber, ...data.payload }) }) } } export default action
jbwyme/action-destinations
packages/core/src/index.ts
export { Destination, fieldsToJsonSchema } from './destination-kit' export { getAuthData } from './destination-kit/parse-settings' export { transform } from './mapping-kit' export { createTestEvent } from './create-test-event' export { createTestIntegration } from './create-test-integration' export { defaultValues } from './defaults' export { IntegrationError, InvalidAuthenticationError, RetryableError } from './errors' export { get } from './get' export { omit } from './omit' export { removeUndefined } from './remove-undefined' export { time, duration } from './time' export { realTypeOf, isObject, isArray, isString } from './real-type-of' export type { RequestOptions } from './request-client' export { default as fetch, Request, Response, Headers } from './fetch' export type { BaseActionDefinition, ActionDefinition, BaseDefinition, DestinationDefinition, ExecuteInput, Subscription, SubscriptionStats, AuthenticationScheme, BasicAuthentication, CustomAuthentication, OAuth2Authentication, OAuth2ClientCredentials, RefreshAccessTokenResult, RequestFn, DecoratedResponse, MinimalInputField } from './destination-kit' export type { DynamicFieldResponse, DynamicFieldItem, InputField, GlobalSetting, RequestExtension } from './destination-kit/types' export type { JSONPrimitive, JSONValue, JSONObject, JSONArray, JSONLike, JSONLikeObject } from './json-object' export type { SegmentEvent } from './segment-event'
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/__tests__/beginCheckout.test.ts
<reponame>jbwyme/action-destinations<filename>packages/destination-actions/src/destinations/google-analytics-4/__tests__/beginCheckout.test.ts import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import ga4 from '../index' const testDestination = createTestIntegration(ga4) const apiSecret = '<KEY>' const measurementId = 'G-TESTTOKEN' describe('GA4', () => { describe('Begin Checkout', () => { it('should handle basic mapping overrides', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Checkout Started', userId: '3456fff', anonymousId: 'anon-567890', type: 'track', properties: { order_id: '50314b8e9bcf000000000000', affiliation: 'Google Store', value: 30, revenue: 25.0, shipping: 3, tax: 2, discount: 2.5, coupon: 'hasbros', currency: 'USD', products: [ { product_id: '507f1f77bcf86cd799439011', sku: '45790-32', name: 'Monopoly: 3rd Edition', price: 19, quantity: 1, category: 'Games', url: 'https://www.example.com/product/path', image_url: 'https://www.example.com/product/path.jpg' } ] } }) const responses = await testDestination.testAction('beginCheckout', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.anonymousId' }, coupon: { '@path': '$.properties.coupon' }, currency: { '@path': '$.properties.currency' }, value: { '@path': '$.properties.revenue' }, items: [ { item_name: { '@path': `$.properties.products.0.name` }, item_category: { '@path': `$.properties.products.0.category` } } ] }, useDefaultMappings: false }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(201) expect(responses[0].request.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "content-type": Array [ "application/json", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.body).toMatchInlineSnapshot( `"{\\"client_id\\":\\"anon-567890\\",\\"events\\":[{\\"name\\":\\"begin_checkout\\",\\"params\\":{\\"coupon\\":\\"hasbros\\",\\"currency\\":\\"USD\\",\\"items\\":[{\\"item_name\\":\\"Monopoly: 3rd Edition\\",\\"item_category\\":\\"Games\\"}],\\"value\\":25}}]}"` ) }) it('should throw an error for invalid currency values', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Checkout Started', userId: '3456fff', type: 'track', properties: { order_id: '5678dd9087-78', coupon: 'SUMMER_FEST', currency: '1234' } }) try { await testDestination.testAction('beginCheckout', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.userId' }, coupon: { '@path': '$.properties.coupon' }, currency: { '@path': '$.properties.currency' } }, useDefaultMappings: true }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe('1234 is not a valid currency code.') } }) it('should throw an error for products missing name and id', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Checkout Started', userId: '3456fff', type: 'track', properties: { order_id: '5678dd9087-78', coupon: 'SUMMER_FEST', currency: 'USD', products: [ { quantity: 2, coupon: 'MOUNTAIN', brand: 'Canvas', category: 'T-Shirt', variant: 'Black', price: 19.98 } ] } }) try { await testDestination.testAction('beginCheckout', { event, settings: { apiSecret, measurementId }, mapping: { client_id: { '@path': '$.anonymousId' }, currency: { '@path': '$.properties.currency' }, value: { '@path': '$.properties.value' }, items: [ { item_brand: { '@path': `$.properties.brand` } } ] }, useDefaultMappings: true }) fail('the test should have thrown an error') } catch (e) { expect(e.message).toBe('One of product name or product id is required for product or impression data.') } }) it('should handle default mappings', async () => { nock('https://www.google-analytics.com/mp/collect') .post(`?measurement_id=${measurementId}&api_secret=${apiSecret}`) .reply(201, {}) const event = createTestEvent({ event: 'Checkout Started', userId: '3456fff', anonymousId: 'anon-567890', type: 'track', properties: { order_id: '50314b8e9bcf000000000000', affiliation: 'Google Store', value: 30, revenue: 25.0, shipping: 3, tax: 2, discount: 2.5, coupon: 'hasbros', currency: 'USD', products: [ { product_id: '507f1f77bcf86cd799439011', sku: '45790-32', name: 'Monopoly: 3rd Edition', price: 19, quantity: 1, category: 'Games', url: 'https://www.example.com/product/path', image_url: 'https://www.example.com/product/path.jpg' } ] } }) const responses = await testDestination.testAction('beginCheckout', { event, settings: { apiSecret, measurementId }, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(201) expect(responses[0].request.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "content-type": Array [ "application/json", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.body).toMatchInlineSnapshot( `"{\\"client_id\\":\\"3456fff\\",\\"events\\":[{\\"name\\":\\"begin_checkout\\",\\"params\\":{\\"coupon\\":\\"hasbros\\",\\"currency\\":\\"USD\\",\\"items\\":[],\\"value\\":30}}]}"` ) }) }) })
jbwyme/action-destinations
packages/cli/src/lib/server.ts
<filename>packages/cli/src/lib/server.ts<gh_stars>0 import express from 'express' import http from 'http' import { once } from 'lodash' import logger from './logger' import path from 'path' import { loadDestination } from './destinations' import { Destination, DestinationDefinition as CloudDestinationDefinition } from '@segment/actions-core' import asyncHandler from './async-handler' import getExchanges from './summarize-http' import ora from 'ora' import chalk from 'chalk' const app = express() app.use(express.json()) const spinner: ora.Ora = ora() const DEFAULT_PORT = 3000 const port = process.env.PORT || DEFAULT_PORT const server = http.createServer(app) const destinationSlug = process.env.DESTINATION as string const directory = process.env.DIRECTORY as string app.post( '/:action', asyncHandler(async (req: express.Request, res: express.Response) => { const actionSlug = req.params.action spinner.start(chalk`Handling ${process.env.DESTINATION}#${actionSlug} action request`) // For now, include the slug in the path, but when we support external repos, we'll have to change this const targetDirectory = path.join(process.cwd(), directory, destinationSlug, 'index.ts') try { const def = await loadDestination(targetDirectory) const destination = new Destination(def as CloudDestinationDefinition) const action = destination.actions[actionSlug] if (!action) { const msg = `${destination.name} action '${actionSlug}' is invalid or not found` spinner.fail(chalk`${msg}`) return res.status(400).send(msg) } await action.execute({ data: req.body.payload || {}, settings: req.body.settings || {}, mapping: req.body.payload || {}, auth: req.body.auth || {} }) const debug = await getExchanges(destination.responses) spinner.succeed(chalk`${destination.name} action '${actionSlug}' completed`) return res.status(200).json(debug) } catch (err) { spinner.fail() return res.status(err.status ?? 500).send(err.message) } }) ) const gracefulShutdown = once((exitCode: number) => { logger.info('Server stopping...') // Stop receiving new requests, allowing inflight requests to finish if (server) { server.close(() => { logger.info('Server stopped') // Leave time for logging / error capture setTimeout(() => process.exit(exitCode), 300) }) } // Forcibly shutdown after 8 seconds (Docker forcibly kills after 10 seconds) setTimeout(() => { logger.crit('Forcibly shutting down') // Leave time for logging / error capture setTimeout(() => process.exit(1), 300) }, 8000) }) // eslint-disable-next-line @typescript-eslint/no-explicit-any function handleUncaught(error: any, crashType: string): void { error.crashType = crashType logger.crit('😱 Server crashed', error) // Gracefully shutdown the server on uncaught errors to allow inflight requests to finish gracefulShutdown(1) } process.on('uncaughtException', (error) => { handleUncaught(error, 'uncaughtException') }) process.on('unhandledRejection', (error) => { handleUncaught(error, 'unhandledRejection') }) // Interrupt signal sent by Ctrl+C process.on('SIGINT', () => gracefulShutdown(0)) server.on('error', (err: Error) => { logger.error(`Server error: ${err.message}`, err) }) server.listen(port, () => { logger.info(`Ready to process POST requests at http://localhost:${port}/<DESTINATION ACTION>`) })
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/createUpdateDevice/generated-types.ts
<reponame>jbwyme/action-destinations // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * ID of the person that this device belongs to. */ person_id: string /** * Unique ID for this device. */ device_id: string /** * The device platform. */ platform: string /** * Timestamp for when the device was last used. Default is current date and time. */ last_used?: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/amplitude/user-agent.ts
import UaParser from '@amplitude/ua-parser-js' interface ParsedUA { os_name?: string os_version?: string device_model?: string } export function parseUserAgentProperties(userAgent?: string): ParsedUA { if (!userAgent) { return {} } // eslint-disable-next-line @typescript-eslint/no-unsafe-call const parser = new UaParser(userAgent) // eslint-disable-next-line @typescript-eslint/no-unsafe-call const device = parser.getDevice() // eslint-disable-next-line @typescript-eslint/no-unsafe-call const os = parser.getOS() return { os_name: os.name, os_version: os.version, device_model: device.model } }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/fullstory/__tests__/fullstory.test.ts
<reponame>jbwyme/action-destinations<filename>packages/browser-destinations/src/destinations/fullstory/__tests__/fullstory.test.ts import * as FullStory from '@fullstory/browser' import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import fullstory, { destination } from '..' import { Subscription } from '../../../lib/browser-destinations' const example: Subscription[] = [ { partnerAction: 'event', name: 'Event', enabled: true, subscribe: 'type = "track"', mapping: { name: { '@path': '$.name' }, properties: { '@path': '$.properties' } } }, { partnerAction: 'setUserVars', name: 'SetUserVars', enabled: true, subscribe: 'type = "identify"', mapping: { displayName: { '@path': '$.traits.name' }, email: { '@path': '$.traits.email' }, traits: { '@path': '$.traits' } } } ] beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://fullstory.com' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) }) test('can load fullstory', async () => { const [event] = await fullstory({ orgId: 'thefullstory.com', subscriptions: example }) jest.spyOn(destination.actions.event, 'perform') jest.spyOn(destination, 'initialize') await event.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() const ctx = await event.track?.( new Context({ type: 'track', properties: { banana: '📞' } }) ) expect(destination.actions.event.perform).toHaveBeenCalled() expect(ctx).not.toBeUndefined() const scripts = window.document.querySelectorAll('script') expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://edge.fullstory.com/s/fs.js" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) }) test('send record events to fullstory on "event"', async () => { const fs = jest.spyOn(FullStory, 'event') const [event] = await fullstory({ orgId: 'thefullstory.com', subscriptions: example }) await event.load(Context.system(), {} as Analytics) await event.track?.( new Context({ type: 'track', name: 'hello!', properties: { banana: '📞' } }) ) expect(fs).toHaveBeenCalledWith('hello!', { banana: '📞' }) }) test('can set user vars', async () => { const fs = jest.spyOn(FullStory, 'setUserVars') const [_, setUserVars] = await fullstory({ orgId: 'thefullstory.com', subscriptions: example }) await setUserVars.load(Context.system(), {} as Analytics) await setUserVars.identify?.( new Context({ type: 'identify', traits: { name: 'Hasbulla', email: 'the<EMAIL>', height: '50cm' } }) ) expect(fs).toHaveBeenCalledWith({ displayName: 'Hasbulla', email: 'the<EMAIL>', height: '50cm', name: 'Hasbulla' }) })
jbwyme/action-destinations
packages/core/src/mapping-kit/validate.ts
<reponame>jbwyme/action-destinations import AggregateError from 'aggregate-error' import { CustomError } from 'ts-custom-error' import { isDirective } from './is-directive' import { isObject, realTypeOf, Dictionary } from '../real-type-of' class ValidationError extends CustomError { constructor(message: string, stack: string[] = []) { super(`/${stack.join('/')} ${message}.`) } } function flatAggregate(errors: Error[]): Error[] { const result: Error[] = [] errors.forEach((error) => { if (error instanceof AggregateError) { result.push(...error) } else { result.push(error) } }) return result } function realTypeOrDirective(value: unknown) { const type = realTypeOf(value) if (type === 'object' && Object.keys(value as object).some((k) => k.startsWith('@'))) { return 'directive' } return type } type DirectiveValidator = (v: unknown, stack?: string[]) => void interface DirectiveValidators { [directive: string]: DirectiveValidator | undefined } const directives: DirectiveValidators = {} function validateDirective(obj: unknown, stack: string[] = []): void { // "allow" non-directive objects so that we can throw a more descriptive error below if (!isDirective(obj) && !isObject(obj)) { const type = realTypeOf(obj) throw new ValidationError(`should be a directive object but it is ${indefiniteArticle(type)} ${type}`, stack) } const keys = Object.keys(obj) const directiveKeys = keys.filter((key) => key.startsWith('@')) if (directiveKeys.length > 1) { throw new ValidationError(`should only have one @-prefixed key but it has ${directiveKeys.length} keys`, stack) } // Check that there aren't other keys besides @directive or _metadata const otherKeys = keys.filter((key) => !key.startsWith('@') && key !== '_metadata') if (otherKeys.length > 0) { throw new ValidationError(`should only have one @-prefixed key but it has ${keys.length} keys`, stack) } const directiveKey = directiveKeys[0] const fn = directives[directiveKey] if (typeof fn !== 'function') { throw new ValidationError(`has an invalid directive: ${directiveKey}`, stack) } fn(obj[directiveKey], stack) } function validateDirectiveOrRaw(v: unknown, stack: string[] = []) { const type = realTypeOrDirective(v) switch (type) { case 'directive': return validateDirective(v, stack) case 'object': case 'array': case 'boolean': case 'string': case 'number': case 'null': return default: throw new ValidationError( `should be a mapping directive or a JSON value but it is ${indefiniteArticle(type)} ${type}`, stack ) } } function validateDirectiveOrString(v: unknown, stack: string[] = []) { const type = realTypeOrDirective(v) switch (type) { case 'directive': return validateDirective(v, stack) case 'string': return default: throw new ValidationError( `should be a string or a mapping directive but it is ${indefiniteArticle(type)} ${type}`, stack ) } } function validateObject(value: unknown, stack: string[] = []) { const type = realTypeOrDirective(value) if (type !== 'object') { throw new ValidationError(`should be an object but it is ${indefiniteArticle(type)} ${type}`, stack) } const obj = value as Dictionary const keys = Object.keys(obj) const directiveKey = keys.find((k) => k.charAt(0) === '@') if (directiveKey) { throw new ValidationError( `shouldn't have directive (@-prefixed) keys but it has ${JSON.stringify(directiveKey)}`, stack ) } const errors: Error[] = [] keys.forEach((k) => { try { validate(obj[k], [...stack, k]) } catch (e) { errors.push(e) } }) if (errors.length) { throw new AggregateError(flatAggregate(errors)) } } interface ValidateFields { [key: string]: { required?: DirectiveValidator optional?: DirectiveValidator } } function validateObjectWithFields(input: unknown, fields: ValidateFields, stack: string[] = []) { validateObject(input, stack) const errors: Error[] = [] const obj = input as Dictionary Object.entries(fields).forEach(([prop, { required, optional }]) => { try { if (required) { if (obj[prop] === undefined) { throw new ValidationError(`should have field ${JSON.stringify(prop)} but it doesn't`, stack) } required(obj[prop], [...stack, prop]) } else if (optional) { if (obj[prop] !== undefined) { optional(obj[prop], [...stack, prop]) } } } catch (error) { errors.push(error) } }) if (errors.length) { throw new AggregateError(flatAggregate(errors)) } } function validateArray(arr: unknown, stack: string[] = []): void { const type = realTypeOf(arr) if (type !== 'array') { throw new ValidationError(`should be an array but it is ${indefiniteArticle(type)} ${type}`, stack) } } function directive(names: string[] | string, fn: DirectiveValidator): void { if (!Array.isArray(names)) { names = [names] } names.forEach((name) => { directives[name] = (v: unknown, stack: string[] = []) => { try { fn(v, [...stack, name]) } catch (e) { if (e instanceof ValidationError || e instanceof AggregateError) { throw e } throw new ValidationError(e.message, stack) } } }) } directive('@if', (v, stack) => { validateObjectWithFields( v, { exists: { optional: validateDirectiveOrRaw }, then: { optional: validateDirectiveOrRaw }, else: { optional: validateDirectiveOrRaw } }, stack ) }) directive('@path', (v, stack) => { validateDirectiveOrString(v, stack) }) directive('@template', (v, stack) => { validateDirectiveOrString(v, stack) }) directive('@literal', (v, stack) => { validateDirectiveOrRaw(v, stack) }) function indefiniteArticle(s: string): string { switch (s.charAt(0)) { case 'a': case 'e': case 'i': case 'o': case 'u': return 'an' default: return 'a' } } export default function validate(mapping: unknown, stack: string[] = []) { switch (realTypeOrDirective(mapping)) { case 'directive': return validateDirective(mapping, stack) case 'object': return validateObject(mapping, stack) case 'array': return validateArray(mapping, stack) default: // All other types are valid "raw" mappings return null } }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/intercom/__tests__/intercom.test.ts
<reponame>jbwyme/action-destinations import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import intercomPlugins, { destination } from '..' import { Subscription } from '../../../lib/browser-destinations' const example: Subscription[] = [ { partnerAction: 'show', name: 'Show', enabled: true, subscribe: 'type = "track"', mapping: { user_id: { '@path': '$.userId' }, event_type: { '@path': '$.event' }, time: { '@path': '$.timestamp' }, event_properties: { '@path': '$.properties' } } } ] beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', // navigate to intercom itself, so we can actually load their app id url: 'https://intercom.com' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) }) test('can load intercom', async () => { const [show] = await intercomPlugins({ // using itercom's app_id from intercom.com app_id: 'tx2p130c', subscriptions: example }) jest.spyOn(destination.actions.show, 'perform') jest.spyOn(destination, 'initialize') await show.load(Context.system(), {} as Analytics) expect(destination.initialize).toHaveBeenCalled() const ctx = await show.track?.( new Context({ type: 'track', properties: { banana: '📞' } }) ) expect(destination.actions.show.perform).toHaveBeenCalled() expect(ctx).not.toBeUndefined() const scripts = window.document.querySelectorAll('script') expect(scripts).toMatchInlineSnapshot(` NodeList [ <script src="https://widget.intercom.io/widget/tx2p130c" status="loaded" type="text/javascript" />, <script> 'hi' </script>, ] `) })
jbwyme/action-destinations
packages/core/src/destination-kit/types.ts
import type { RequestOptions } from '../request-client' import type { JSONObject } from '../json-object' import { AuthTokens } from './parse-settings' export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K> export interface Result { output?: JSONObject | string | null | undefined error?: JSONObject | null } export interface ExecuteInput<Settings, Payload> { /** The subscription mapping definition */ readonly mapping?: JSONObject /** The global destination settings */ readonly settings: Settings /** The transformed input data, based on `mapping` + `event` */ payload: Payload /** The page used in dynamic field requests */ page?: string /** The data needed in OAuth requests */ readonly auth?: AuthTokens } export interface DynamicFieldResponse { body: { data: DynamicFieldItem[] pagination: { nextPage?: string } } } export interface DynamicFieldItem { label: string value: string } /** The shape of authentication and top-level settings */ export interface GlobalSetting { /** A short, human-friendly label for the field */ label: string /** A human-friendly description of the field */ description: string /** A subset of the available DestinationMetadataOption types */ type: 'boolean' | 'string' | 'password' | 'number' /** Whether or not the field accepts more than one of its `type` */ multiple?: boolean /** * A predefined set of options for the setting. * Only relevant for `type: 'string'` or `type: 'number'`. */ choices?: Array<{ /** The value of the option */ value: string | number /** A human-friendly label for the option */ label: string }> required?: boolean default?: string | number | boolean properties?: InputField['properties'] format?: InputField['format'] } /** The supported field type names */ export type FieldTypeName = 'string' | 'text' | 'number' | 'integer' | 'datetime' | 'boolean' | 'password' | 'object' /** The shape of an input field definition */ export interface InputField { /** A short, human-friendly label for the field */ label: string /** A human-friendly description of the field */ description: string /** The data type for the field */ type: FieldTypeName /** Whether null is allowed or not */ allowNull?: boolean /** Whether or not the field accepts multiple values (an array of `type`) */ multiple?: boolean /** An optional default value for the field */ default?: FieldValue /** A placeholder display value that suggests what to input */ placeholder?: string /** Whether or not the field supports dynamically fetching options */ dynamic?: boolean /** Whether or not the field is required */ required?: boolean /** * Optional definition for the properties of `type: 'object'` fields * (also arrays of objects when using `multiple: true`) * Note: this part of the schema is not persisted outside the code * but is used for validation and typedefs */ properties?: Record<string, Optional<InputField, 'description'>> /** * Format option to specify more nuanced 'string' types * @see {@link https://github.com/ajv-validator/ajv/tree/v6#formats} */ format?: | 'date' // full-date according to RFC3339. | 'time' // time with optional time-zone. | 'date-time' // date-time from the same source (time-zone is mandatory). date, time and date-time validate ranges in full mode and only regexp in fast mode (see options). | 'uri' // full URI. | 'uri-reference' // URI reference, including full and relative URIs. | 'uri-template' // URI template according to RFC6570 | 'email' // email address. | 'hostname' // host name according to RFC1034. | 'ipv4' // IP address v4. | 'ipv6' // IP address v6. | 'regex' // tests whether a string is a valid regular expression by passing it to RegExp constructor. | 'uuid' // Universally Unique IDentifier according to RFC4122. | 'password' // hint to the UI to hide/obfuscate input strings | 'text' // longer strings } export type FieldValue = string | number | boolean | object | Directive export interface IfDirective { '@if': { exists?: FieldValue then: FieldValue else?: FieldValue } } export interface TemplateDirective { '@template': string } export interface PathDirective { '@path': string } export type Directive = IfDirective | TemplateDirective | PathDirective /** * A function to configure a request client instance with options * that will be applied to every request made by that instance */ export type RequestExtension<Settings, Payload = unknown> = (data: ExecuteInput<Settings, Payload>) => RequestOptions
jbwyme/action-destinations
packages/destination-actions/src/destinations/amplitude/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Settings { /** * Amplitude project API key. You can find this key in the "General" tab of your Amplitude project. */ apiKey: string /** * Amplitude project secret key. You can find this key in the "General" tab of your Amplitude project. */ secretKey: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/braze/__tests__/braze.test.ts
import nock from 'nock' import { createTestEvent, createTestIntegration } from '@segment/actions-core' import Braze from '../index' const testDestination = createTestIntegration(Braze) const receivedAt = '2021-08-03T17:40:04.055Z' const settings = { app_id: 'my-app-id', api_key: 'my-api-key', endpoint: 'https://example.com' } describe(Braze.name, () => { describe('updateUserProfile', () => { it('should work with default mappings', async () => { nock('https://example.com').post('/users/track').reply(200, {}) const event = createTestEvent({ type: 'identify', receivedAt }) const responses = await testDestination.testAction('updateUserProfile', { event, settings, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(200) expect(responses[0].data).toMatchObject({}) expect(responses[0].options.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "authorization": Array [ "Bearer my-api-key", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.json).toMatchInlineSnapshot(` Object { "attributes": Array [ Object { "_update_existing_only": false, "braze_id": undefined, "country": "United States", "current_location": Object { "latitude": 40.2964197, "longitude": -76.9411617, }, "date_of_first_session": undefined, "date_of_last_session": undefined, "dob": undefined, "email": undefined, "email_click_tracking_disabled": undefined, "email_open_tracking_disabled": undefined, "email_subscribe": undefined, "external_id": "user1234", "facebook": undefined, "first_name": undefined, "gender": undefined, "home_city": undefined, "image_url": undefined, "language": undefined, "last_name": undefined, "marked_email_as_spam_at": undefined, "phone": undefined, "push_subscribe": undefined, "push_tokens": undefined, "time_zone": undefined, "twitter": undefined, "user_alias": undefined, }, ], } `) }) it('should require one of braze_id, user_alias, or external_id', async () => { nock('https://example.com').post('/users/track').reply(200, {}) const event = createTestEvent({ type: 'identify', receivedAt }) await expect( testDestination.testAction('updateUserProfile', { event, settings, mapping: {} }) ).rejects.toThrowErrorMatchingInlineSnapshot( `"One of \\"external_id\\" or \\"user_alias\\" or \\"braze_id\\" is required."` ) }) }) describe('trackEvent', () => { it('should work with default mappings', async () => { nock('https://example.com').post('/users/track').reply(200, {}) const event = createTestEvent({ event: 'Test Event', type: 'track', receivedAt }) const responses = await testDestination.testAction('trackEvent', { event, settings, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(200) expect(responses[0].data).toMatchObject({}) expect(responses[0].options.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "authorization": Array [ "Bearer my-api-key", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.json).toMatchInlineSnapshot(` Object { "events": Array [ Object { "_update_existing_only": false, "app_id": "my-app-id", "braze_id": undefined, "external_id": "user1234", "name": "<NAME>", "properties": Object {}, "time": "2021-08-03T17:40:04.055Z", "user_alias": undefined, }, ], } `) }) }) describe('trackPurchase', () => { it('should work with default mappings', async () => { nock('https://example.com').post('/users/track').reply(200, {}) const event = createTestEvent({ event: 'Order Completed', type: 'track', receivedAt }) const responses = await testDestination.testAction('trackEvent', { event, settings, useDefaultMappings: true }) expect(responses.length).toBe(1) expect(responses[0].status).toBe(200) expect(responses[0].data).toMatchObject({}) expect(responses[0].options.headers).toMatchInlineSnapshot(` Headers { Symbol(map): Object { "authorization": Array [ "Bearer my-api-key", ], "user-agent": Array [ "Segment", ], }, } `) expect(responses[0].options.json).toMatchInlineSnapshot(` Object { "events": Array [ Object { "_update_existing_only": false, "app_id": "my-app-id", "braze_id": undefined, "external_id": "user1234", "name": "Order Completed", "properties": Object {}, "time": "2021-08-03T17:40:04.055Z", "user_alias": undefined, }, ], } `) }) }) })
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/viewPromotion/index.ts
import { ActionDefinition, IntegrationError } from '@segment/actions-core' import { CURRENCY_ISO_CODES } from '../constants' import { PromotionProductItem } from '../ga4-types' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' /** * Following GA4 View Promotion Spec at: * https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events#view_promotion */ const action: ActionDefinition<Settings, Payload> = { title: 'View Promotion', description: 'Send view promotion events to GA4 to make the most of the ecommerce reports in Google Analytics', defaultSubscription: 'type = "track" and event = "Promotion Viewed"', fields: { client_id: { label: 'Client ID', description: 'Uniquely identifies a user instance of a web client.', type: 'string', required: true, default: { '@if': { exists: { '@path': '$.userId' }, then: { '@path': '$.userId' }, else: { '@path': '$.anonymousId' } } } }, creative_name: { label: 'Creative Name', type: 'string', description: 'The name of the promotional creative.' }, creative_slot: { label: 'Creative Slot', type: 'string', description: 'The name of the promotional creative slot associated with the event.', default: { '@path': '$.properties.creative' } }, location_id: { label: 'Location ID', type: 'string', description: 'The ID of the location.', default: { '@path': '$.properties.position' } }, promotion_id: { label: 'Promotion ID', type: 'string', description: 'The ID of the promotion associated with the event.', default: { '@path': '$.properties.promotion_id' } }, promotion_name: { label: 'Promotion Name', type: 'string', description: 'The name of the promotion associated with the event.', default: { '@path': '$.properties.name' } }, items: { label: 'Products', description: 'The list of products in the event.', type: 'object', multiple: true, required: true, properties: { item_id: { label: 'Product ID', type: 'string', description: 'Identifier for the product being purchased.' }, item_name: { label: 'Name', type: 'string', description: 'Name of the product being purchased.' }, affiliation: { label: 'Affiliation', type: 'string', description: 'A product affiliation to designate a supplying company or brick and mortar store location.' }, coupon: { label: 'Coupon', type: 'string', description: 'Coupon code used for a purchase.' }, currency: { label: 'Currency', type: 'string', description: 'Currency of the purchase or items associated with the event, in 3-letter ISO 4217 format.' }, creative_name: { label: 'Creative Name', type: 'string', description: 'The name of the promotional creative.' }, creative_slot: { label: 'Creative Slot', type: 'string', description: 'The name of the promotional creative slot associated with the item.' }, discount: { label: 'Discount', type: 'number', description: 'Monetary value of discount associated with a purchase.' }, index: { label: 'Index', type: 'number', description: 'The index/position of the item in a list.' }, item_brand: { label: 'Brand', type: 'string', description: 'Brand associated with the product.' }, item_category: { label: 'Category', type: 'string', description: 'The category of the item.' }, item_category2: { label: 'Category 2', type: 'string', description: 'The second category hierarchy or additional taxonomy for the item.' }, item_category3: { label: 'Category 3', type: 'string', description: 'The third category hierarchy or additional taxonomy for the item.' }, item_category4: { label: 'Category 4', type: 'string', description: 'The fourth category hierarchy or additional taxonomy for the item.' }, item_category5: { label: 'Category 5', type: 'string', description: 'The fifth category hierarchy or additional taxonomy for the item.' }, item_list_id: { label: 'Item List ID', type: 'string', description: 'The ID of the list in which the item was presented to the user.' }, item_list_name: { label: 'Item List Name', type: 'string', description: 'The name of the list in which the item was presented to the user.' }, item_variant: { label: 'Variant', type: 'string', description: 'Variant of the product (e.g. Black).' }, location_id: { label: 'Location ID', type: 'string', description: 'The location associated with the item.' }, price: { label: 'Price', type: 'number', description: 'Price of the product being purchased, in units of the specified currency parameter.' }, promotion_id: { label: 'Promotion ID', type: 'string', description: 'The ID of the promotion associated with the item.' }, promotion_name: { label: 'Promotion Name', type: 'string', description: 'The name of the promotion associated with the item.' }, quantity: { label: 'Quantity', type: 'number', description: 'Item Quantity' } } } }, perform: (request, { payload }) => { let googleItems: PromotionProductItem[] = [] if (payload.items) { googleItems = payload.items.map((product) => { if (product.item_name === undefined && product.item_id === undefined) { throw new IntegrationError('One of item id or item name is required.', 'Misconfigured required field', 400) } if (product.currency && !CURRENCY_ISO_CODES.includes(product.currency)) { throw new IntegrationError(`${product.currency} is not a valid currency code.`, 'Incorrect value format', 400) } return product as PromotionProductItem }) } return request('https://www.google-analytics.com/mp/collect', { method: 'POST', json: { client_id: payload.client_id, events: [ { name: 'view_promotion', params: { creative_name: payload.creative_name, creative_slot: payload.creative_slot, location_id: payload.location_id, promotion_id: payload.promotion_id, promotion_name: payload.promotion_name, items: googleItems } } ] } }) } } export default action
jbwyme/action-destinations
packages/browser-destinations/src/destinations/index.ts
import type { BrowserDestinationDefinition } from '../lib/browser-destinations' import path from 'path' type MetadataId = string export interface ManifestEntry { // eslint-disable-next-line @typescript-eslint/no-explicit-any definition: BrowserDestinationDefinition<any, any> directory: string path: string } export const manifest: Record<MetadataId, ManifestEntry> = {} function register(id: MetadataId, destinationPath: string) { // eslint-disable-next-line @typescript-eslint/no-var-requires const definition = require(destinationPath).destination const resolvedPath = require.resolve(destinationPath) const [directory] = path.dirname(resolvedPath).split(path.sep).reverse() manifest[id] = { definition, directory, path: resolvedPath } } // TODO figure out if it's possible to colocate the Amplitude web action with the rest of its destination definition (in `./packages/destination-actions`) register('5f7dd6d21ad74f3842b1fc47', './amplitude-plugins') register('60fb01aec459242d3b6f20c1', './braze') register('60f9d0d048950c356be2e4da', './braze-cloud-plugins')
jbwyme/action-destinations
packages/destination-actions/src/destinations/pipedrive/index.ts
import createUpdateOrganization from './createUpdateOrganization' import createUpdatePerson from './createUpdatePerson' import type { DestinationDefinition } from '@segment/actions-core' import type { Settings } from './generated-types' const destination: DestinationDefinition<Settings> = { name: 'Pipedrive', mode: 'cloud', authentication: { scheme: 'custom', fields: { domain: { label: 'Domain', description: 'Pipedrive domain. This is found in Pipedrive in Settings > Company settings > Company domain.', type: 'string', // minLength: 1, required: true }, apiToken: { label: 'API Token', description: 'Pipedrive API token. This is found in Pipedrive in Settings > Personal preferences > API > Your personal API token.', type: 'string', // minLength: 20, required: true } }, testAuthentication: (request, { settings }) => { return request(`https://${settings.domain}.pipedrive.com/api/v1/users/me`) } }, extendRequest({ settings }) { return { searchParams: { api_token: settings.apiToken } } }, actions: { createUpdateOrganization, createUpdatePerson } } export default destination
jbwyme/action-destinations
packages/destination-actions/src/destinations/pipedrive/createUpdateOrganization/generated-types.ts
<gh_stars>0 // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * Identifier used to find existing organization in Pipedrive. Typically this is the name but it can also be a custom field value. Custom organization fields may be included by using the long hash keys of the custom fields. These look like "33595c732cd7a027c458ea115a48a7f8a254fa86". */ identifier: string /** * Name of the organization */ name: string /** * ID of the user who will be marked as the owner of this organization. Default is the user who ownes the API token. */ owner_id?: number /** * If the organization is created, use this timestamp as the creation timestamp. Format: YYY-MM-DD HH:MM:SS */ add_time?: string }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/fullstory/event/generated-types.ts
<gh_stars>0 // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * The name of the event to be tracked */ name: string /** * A propeties object containing a payload */ properties?: { [k: string]: unknown } }
jbwyme/action-destinations
packages/destination-subscriptions/src/__tests__/validate.test.ts
<filename>packages/destination-subscriptions/src/__tests__/validate.test.ts<gh_stars>0 import { validate as originalValidate } from '../index' // Helper to avoid caring about types in tests const validate = (ast: any, data: any): boolean => originalValidate(ast, data) test('should handle error in ast', () => { const ast = { error: new Error("Cannot read property 'type' of undefined") } expect(validate(ast, { properties: { value: 'x' } })).toEqual(false) }) test('should handle undefined event', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '=', value: 'x' } ] } expect(validate(ast, undefined)).toEqual(false) }) test('should handle empty string as event', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '=', value: 'x' } ] } expect(validate(ast, '')).toEqual(false) }) test('should handle empty event', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '=', value: 'x' } ] } expect(validate(ast, {})).toEqual(false) }) test('operators - equals (strings)', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '=', value: 'x' } ] } expect(validate(ast, { properties: { value: 'x' } })).toEqual(true) expect(validate(ast, { properties: { value: 'y' } })).toEqual(false) }) test('operators - equals (numbers)', () => { for (const value of ['123', 123]) { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '=', value } ] } expect(validate(ast, { properties: { value: 123 } })).toEqual(true) expect(validate(ast, { properties: { value: '123' } })).toEqual(true) expect(validate(ast, { properties: { value: 0 } })).toEqual(false) } }) test('operators - not equals (strings)', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '!=', value: 'x' } ] } expect(validate(ast, { properties: { value: 'x' } })).toEqual(false) expect(validate(ast, { properties: { value: 'y' } })).toEqual(true) }) test('operators - not equals (numbers)', () => { for (const value of ['123', 123]) { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '!=', value } ] } expect(validate(ast, { properties: { value: 123 } })).toEqual(false) expect(validate(ast, { properties: { value: '123' } })).toEqual(false) expect(validate(ast, { properties: { value: 456 } })).toEqual(true) expect(validate(ast, { properties: { value: '456' } })).toEqual(true) } }) test('operators - less than', () => { for (const value of ['10', 10]) { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '<', value } ] } expect(validate(ast, { properties: { value: 5 } })).toEqual(true) expect(validate(ast, { properties: { value: '5' } })).toEqual(true) expect(validate(ast, { properties: { value: 10 } })).toEqual(false) expect(validate(ast, { properties: { value: '10' } })).toEqual(false) } }) test('operators - less than or equal', () => { for (const value of ['10', 10]) { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '<=', value } ] } expect(validate(ast, { properties: { value: 5 } })).toEqual(true) expect(validate(ast, { properties: { value: '5' } })).toEqual(true) expect(validate(ast, { properties: { value: 10 } })).toEqual(true) expect(validate(ast, { properties: { value: '10' } })).toEqual(true) expect(validate(ast, { properties: { value: 11 } })).toEqual(false) expect(validate(ast, { properties: { value: '11' } })).toEqual(false) } }) test('operators - greater than', () => { for (const value of ['10', 10]) { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '>', value } ] } expect(validate(ast, { properties: { value: 11 } })).toEqual(true) expect(validate(ast, { properties: { value: '11' } })).toEqual(true) expect(validate(ast, { properties: { value: 10 } })).toEqual(false) expect(validate(ast, { properties: { value: '10' } })).toEqual(false) expect(validate(ast, { properties: { value: 5 } })).toEqual(false) expect(validate(ast, { properties: { value: '5' } })).toEqual(false) } }) test('operators - greater than or equal', () => { for (const value of ['10', 10]) { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: '>=', value } ] } expect(validate(ast, { properties: { value: 11 } })).toEqual(true) expect(validate(ast, { properties: { value: '11' } })).toEqual(true) expect(validate(ast, { properties: { value: 10 } })).toEqual(true) expect(validate(ast, { properties: { value: '10' } })).toEqual(true) expect(validate(ast, { properties: { value: 5 } })).toEqual(false) expect(validate(ast, { properties: { value: '5' } })).toEqual(false) } }) test('operators - contains', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'contains', value: 'b' } ] } expect(validate(ast, { properties: { value: 'abc' } })).toEqual(true) expect(validate(ast, { properties: { value: 'xyz' } })).toEqual(false) }) test('operators - not contains', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'not_contains', value: 'b' } ] } expect(validate(ast, { properties: { value: 'abc' } })).toEqual(false) expect(validate(ast, { properties: { value: 'xyz' } })).toEqual(true) }) test('operators - starts with', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'starts_with', value: 'x' } ] } expect(validate(ast, { properties: { value: 'xabc' } })).toEqual(true) expect(validate(ast, { properties: { value: 'abc' } })).toEqual(false) }) test('operators - not starts with', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'not_starts_with', value: 'x' } ] } expect(validate(ast, { properties: { value: 'xabc' } })).toEqual(false) expect(validate(ast, { properties: { value: 'abc' } })).toEqual(true) }) test('operators - ends with', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'ends_with', value: 'x' } ] } expect(validate(ast, { properties: { value: 'abcx' } })).toEqual(true) expect(validate(ast, { properties: { value: 'abc' } })).toEqual(false) }) test('operators - not ends with', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'not_ends_with', value: 'x' } ] } expect(validate(ast, { properties: { value: 'abcx' } })).toEqual(false) expect(validate(ast, { properties: { value: 'abc' } })).toEqual(true) }) test('operators - exists', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'exists' } ] } expect(validate(ast, { properties: { value: 'abcx' } })).toEqual(true) expect(validate(ast, { properties: {} })).toEqual(false) expect(validate(ast, { properties: { value: null } })).toEqual(false) }) test('operators - not exists', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'value', operator: 'not_exists' } ] } expect(validate(ast, { properties: { value: 'abcx' } })).toEqual(false) expect(validate(ast, { properties: {} })).toEqual(true) expect(validate(ast, { properties: { value: null } })).toEqual(true) }) test('event type = "track"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-type', operator: '=', value: 'track' } ] } expect(validate(ast, { type: 'track' })).toEqual(true) expect(validate(ast, { type: 'identify' })).toEqual(false) }) test('event type = "track" or "identify"', () => { const ast = { type: 'group', operator: 'or', children: [ { type: 'event-type', operator: '=', value: 'track' }, { type: 'event-type', operator: '=', value: 'identify' } ] } expect(validate(ast, { type: 'track' })).toEqual(true) expect(validate(ast, { type: 'identify' })).toEqual(true) expect(validate(ast, { type: 'group' })).toEqual(false) }) test('event type = not "group"', () => { const ast = { type: 'group', operator: 'or', children: [ { type: 'event-type', operator: '!=', value: 'group' } ] } expect(validate(ast, { type: 'track' })).toEqual(true) expect(validate(ast, { type: 'identify' })).toEqual(true) expect(validate(ast, { type: 'group' })).toEqual(false) }) test('event = "Page Viewed"', () => { const ast = { type: 'group', operator: 'or', children: [ { type: 'event', operator: '=', value: 'Page Viewed' } ] } expect(validate(ast, { event: 'Page Viewed' })).toEqual(true) expect(validate(ast, { event: 'Product Added' })).toEqual(false) }) test('event = "Page Viewed" or "Product Viewed"', () => { const ast = { type: 'group', operator: 'or', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'event', operator: '=', value: 'Product Viewed' } ] } expect(validate(ast, { event: 'Page Viewed' })).toEqual(true) expect(validate(ast, { event: 'Product Viewed' })).toEqual(true) expect(validate(ast, { event: 'Product Added' })).toEqual(false) }) test('event = "Page Viewed" or event type = "track"', () => { const ast = { type: 'group', operator: 'or', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'event-type', operator: '=', value: 'track' } ] } expect(validate(ast, { event: 'Page Viewed' })).toEqual(true) expect(validate(ast, { type: 'track' })).toEqual(true) expect(validate(ast, { event: 'Product Added' })).toEqual(false) }) test('event = "Page Viewed" and event type = "track"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'event-type', operator: '=', value: 'track' } ] } expect(validate(ast, { event: 'Page Viewed' })).toEqual(false) expect(validate(ast, { type: 'track' })).toEqual(false) expect(validate(ast, { event: 'Page Viewed', type: 'track' })).toEqual(true) }) test('event = "Page Viewed" and event property "name" = "Catalog"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'event-property', name: 'name', operator: '=', value: 'Catalog' } ] } expect( validate(ast, { event: 'Page Viewed', properties: { name: 'Catalog' } }) ).toEqual(true) expect(validate(ast, { event: 'Page Viewed' })).toEqual(false) expect( validate(ast, { event: 'Page Viewed', properties: { name: 'Other' } }) ).toEqual(false) }) test('event = "Page Viewed" and event property "name" = "Catalog" or "Home"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'group', operator: 'or', children: [ { type: 'event-property', name: 'name', operator: '=', value: 'Catalog' }, { type: 'event-property', name: 'name', operator: '=', value: 'Home' } ] } ] } expect( validate(ast, { event: 'Page Viewed', properties: { name: 'Catalog' } }) ).toEqual(true) expect( validate(ast, { event: 'Page Viewed', properties: { name: 'Home' } }) ).toEqual(true) expect( validate(ast, { event: 'Page Viewed', properties: { name: 'Other' } }) ).toEqual(false) }) test('event = "Page Viewed" and event context "ip" = "1.1.1.1"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'event-context', name: 'ip', operator: '=', value: '1.1.1.1' } ] } expect( validate(ast, { event: 'Page Viewed', context: { ip: '1.1.1.1' } }) ).toEqual(true) expect(validate(ast, { event: 'Page Viewed' })).toEqual(false) expect( validate(ast, { event: 'Page Viewed', context: { ip: '8.8.8.8' } }) ).toEqual(false) }) test('event = "Page Viewed" and event context "ip" = "1.1.1.1" or "2.2.2.2"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'group', operator: 'or', children: [ { type: 'event-context', name: 'ip', operator: '=', value: '1.1.1.1' }, { type: 'event-property', name: 'ip', operator: '=', value: '2.2.2.2' } ] } ] } expect( validate(ast, { event: 'Page Viewed', context: { ip: '1.1.1.1' } }) ).toEqual(true) expect( validate(ast, { event: 'Page Viewed', context: { ip: '2.2.2.2' } }) ).toEqual(false) expect(validate(ast, { event: 'Page Viewed' })).toEqual(false) expect( validate(ast, { event: 'Page Viewed', context: { ip: '8.8.8.8' } }) ).toEqual(false) }) test('event type = "track" and event = "Page Viewed" or event = "Order Completed"', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-type', operator: '=', value: 'track' }, { type: 'group', operator: 'or', children: [ { type: 'event', operator: '=', value: 'Page Viewed' }, { type: 'event', operator: '=', value: 'Order Completed' } ] } ] } expect( validate(ast, { type: 'track', event: 'Page Viewed' }) ).toEqual(true) }) test('pull properties from `traits` object for "identify" and "group" events', () => { const ast = { type: 'group', operator: 'and', children: [ { type: 'event-property', name: 'name', operator: '=', value: '<NAME>' } ] } expect( validate(ast, { type: 'identify', traits: { name: '<NAME>' } }) ).toEqual(true) expect( validate(ast, { type: 'group', traits: { name: '<NAME>' } }) ).toEqual(true) expect(validate(ast, { event: 'Page Viewed' })).toEqual(false) expect( validate(ast, { type: 'identify', traits: { name: 'Demogorgon' } }) ).toEqual(false) })
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/__tests__/trackEvent.test.ts
<reponame>jbwyme/action-destinations import appboy from '@braze/web-sdk' import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import brazeDestination from '../index' describe('trackEvent', () => { beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://segment.com' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) // we're not really testing that appboy loads here, so we'll just mock it out jest.spyOn(appboy, 'initialize').mockImplementation(() => true) jest.spyOn(appboy, 'openSession').mockImplementation(() => true) }) test('changes the external_id when present', async () => { const customEvent = jest.spyOn(appboy, 'logCustomEvent').mockReturnValue(true) const [trackEvent] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', sdkVersion: '3.3', subscriptions: [ { partnerAction: 'trackEvent', name: 'Log Custom Event', enabled: true, subscribe: 'type = "track"', mapping: { eventName: { '@path': '$.event' }, eventProperties: { '@path': '$.properties' } } } ] }) await trackEvent.load(Context.system(), {} as Analytics) await trackEvent.track?.( new Context({ type: 'track', event: 'UFC', properties: { goat: 'hasbulla' } }) ) expect(customEvent).toHaveBeenCalledWith('UFC', { goat: 'hasbulla' }) }) })
jbwyme/action-destinations
packages/browser-destinations/src/destinations/braze/__tests__/updateUserProfile.test.ts
import appboy from '@braze/web-sdk' import { Analytics, Context } from '@segment/analytics-next' import * as jsdom from 'jsdom' import brazeDestination from '../index' describe('updateUserProfile', () => { let userMock: appboy.User const subscriptions = [ { partnerAction: 'updateUserProfile', name: 'Update User Profile', enabled: true, subscribe: 'type = "identify"', mapping: { country: { '@path': '$.traits.country' }, current_location: { '@path': '$.traits.current_location' }, custom_attributes: { '@path': '$.traits.custom_attributes' }, dob: { '@path': '$.traits.dob' }, email: { '@path': '$.traits.email' }, email_subscribe: { '@path': '$.traits.email_subscribe' }, first_name: { '@path': '$.traits.first_name' }, gender: { '@path': '$.traits.gender' }, home_city: { '@path': '$.traits.home_city' }, image_url: { '@path': '$.traits.image_url' }, language: { '@path': '$.traits.language' }, last_name: { '@path': '$.traits.last_name' }, phone: { '@path': '$.traits.phone' }, push_subscribe: { '@path': '$.traits.push_subscribe' } } } ] beforeEach(async () => { jest.restoreAllMocks() jest.resetAllMocks() const html = ` <!DOCTYPE html> <head> <script>'hi'</script> </head> <body> </body> </html> `.trim() const jsd = new jsdom.JSDOM(html, { runScripts: 'dangerously', resources: 'usable', url: 'https://segment.com' }) const windowSpy = jest.spyOn(window, 'window', 'get') windowSpy.mockImplementation(() => jsd.window as unknown as Window & typeof globalThis) // we're not really testing that appboy loads here, so we'll just mock it out userMock = { setAvatarImageUrl: jest.fn(), setCountry: jest.fn(), setDateOfBirth: jest.fn(), setCustomUserAttribute: jest.fn(), setEmailNotificationSubscriptionType: jest.fn(), setEmail: jest.fn(), setFirstName: jest.fn(), setGender: jest.fn(), setLastName: jest.fn(), setHomeCity: jest.fn(), setLanguage: jest.fn(), setLastKnownLocation: jest.fn(), setPhoneNumber: jest.fn(), setPushNotificationSubscriptionType: jest.fn() } as unknown as appboy.User jest.spyOn(appboy, 'initialize').mockImplementation(() => true) jest.spyOn(appboy, 'openSession').mockImplementation(() => true) jest.spyOn(appboy, 'getUser').mockImplementation(() => userMock) }) test('changes the external_id when present', async () => { const changeUser = jest.spyOn(appboy, 'changeUser').mockImplementationOnce(() => {}) const [trackPurchase] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions: [ { partnerAction: 'updateUserProfile', name: 'Log User', enabled: true, subscribe: 'type = "identify"', mapping: { external_id: { '@path': '$.traits.external_id' } } } ] }) await trackPurchase.load(Context.system(), {} as Analytics) await trackPurchase.identify?.( new Context({ type: 'identify', traits: { external_id: 'xt_123' } }) ) expect(changeUser).toHaveBeenCalledWith('xt_123') }) test('can change user traits', async () => { const [trackPurchase] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions }) await trackPurchase.load(Context.system(), {} as Analytics) await trackPurchase.identify?.( new Context({ type: 'identify', traits: { external_id: 'xt_123', country: 'BRA', current_location: { latitude: -23.54, longitude: -46.65 }, custom_attributes: { greeting: 'oi' }, dob: '01/01/2000', email: '<EMAIL>', email_subscribe: true, first_name: 'Foo', gender: 'M', home_city: 'Miami', image_url: 'img_url', language: 'english', last_name: 'Bar', phone: '555 5555', push_subscribe: true } }) ) expect(userMock.setAvatarImageUrl).toHaveBeenCalledWith('img_url') expect(userMock.setCountry).toHaveBeenCalledWith('BRA') expect(userMock.setDateOfBirth).toHaveBeenCalledWith(2000, 1, 1) expect(userMock.setCustomUserAttribute).toHaveBeenCalledWith('greeting', 'oi') expect(userMock.setEmailNotificationSubscriptionType).toHaveBeenCalledWith(true) expect(userMock.setEmail).toHaveBeenCalledWith('<EMAIL>') expect(userMock.setFirstName).toHaveBeenCalledWith('Foo') expect(userMock.setGender).toHaveBeenCalledWith('M') expect(userMock.setLastName).toHaveBeenCalledWith('Bar') expect(userMock.setHomeCity).toHaveBeenCalledWith('Miami') expect(userMock.setLanguage).toHaveBeenCalledWith('english') expect(userMock.setLastKnownLocation).toHaveBeenCalledWith(-23.54, -46.65) expect(userMock.setPhoneNumber).toHaveBeenCalledWith('555 5555') expect(userMock.setPushNotificationSubscriptionType).toHaveBeenCalledWith(true) }) test('can set gender', async () => { const [trackPurchase] = await brazeDestination({ api_key: 'b_123', endpoint: 'endpoint', subscriptions }) await trackPurchase.load(Context.system(), {} as Analytics) await trackPurchase.identify?.( new Context({ type: 'identify', traits: { gender: 'Male' } }) ) expect(userMock.setGender).toHaveBeenCalledWith('M') await trackPurchase.identify?.( new Context({ type: 'identify', traits: { gender: 'prefer not to say' } }) ) expect(userMock.setGender).toHaveBeenCalledWith('P') await trackPurchase.identify?.( new Context({ type: 'identify', traits: { gender: 'not defined on mapping' } }) ) expect(userMock.setGender).toHaveBeenCalledWith('not defined on mapping') await trackPurchase.identify?.( new Context({ type: 'identify', traits: { gender: null } }) ) expect(userMock.setGender).toHaveBeenCalledWith(null) }) })
jbwyme/action-destinations
packages/destination-subscriptions/src/generate-fql.ts
import { Subscription, GroupCondition, EventTypeCondition, EventCondition, EventPropertyCondition, EventTraitCondition, EventContextCondition, Operator, ErrorCondition } from './types' const stringifyValue = ( value: string | boolean | number | undefined ): string => { if (typeof value === 'boolean' || typeof value === 'number') { return String(value) } return `"${value}"` } const fqlExpression = ( name: string, operator: Operator, value: string | boolean | number | undefined ): string => { switch (operator) { case 'contains': return `contains(${name}, ${stringifyValue(value)})` case 'not_contains': return `!contains(${name}, ${stringifyValue(value)})` case 'exists': return `${name} != null` case 'not_exists': return `${name} = null` case 'starts_with': return `match(${name}, "${String(value)}*")` case 'not_starts_with': return `!match(${name}, "${String(value)}*")` case 'ends_with': return `match(${name}, "*${String(value)}")` case 'not_ends_with': return `!match(${name}, "*${String(value)}")` case '<': case '>': case '<=': case '>=': return `${name} ${operator} ${Number(value)}` default: return `${name} ${operator} ${stringifyValue(value)}` } } const stringifyGroupNode = (node: GroupCondition): string => { return node.children .map(childNode => { if (childNode.type === 'group') { return `(${stringifyGroupNode(childNode)})` } return stringifyChildNode(childNode) }) .join(` ${node.operator} `) } const stringifyChildNode = ( node: | EventTypeCondition | EventCondition | EventPropertyCondition | EventTraitCondition | EventContextCondition ): string => { let result = '' switch (node.type) { case 'event': { result += fqlExpression('event', node.operator, node.value) break } case 'event-type': { result += fqlExpression('type', node.operator, node.value) break } case 'event-property': { result += fqlExpression( `properties.${node.name}`, node.operator, node.value ) break } case 'event-trait': { result += fqlExpression(`traits.${node.name}`, node.operator, node.value) break } case 'event-context': { result += fqlExpression(`context.${node.name}`, node.operator, node.value) break } default: throw new Error('Unknown condition type') } return result } const numberOfParens = (string: string): number => { let parens = 0 for (const char of string.split('')) { if (char === '(' || char === ')') { parens++ } } return parens } const generateFql = (ast: Subscription): string => { if ((ast as ErrorCondition).error) { throw (ast as ErrorCondition).error } const fql = stringifyGroupNode(ast as GroupCondition) if (fql.startsWith('(') && fql.endsWith(')') && numberOfParens(fql) === 2) { return fql.slice(1, -1) } return fql } export default generateFql
jbwyme/action-destinations
packages/core/src/segment-event.ts
<filename>packages/core/src/segment-event.ts<gh_stars>0 import { JSONValue } from './json-object' type ID = string | null | undefined type CompactMetricType = 'g' | 'c' interface CompactMetric { m: string // metric name v: number // value k: CompactMetricType t: string[] // tags e: number // timestamp in unit milliseconds } export type Integrations = { All?: boolean [integration: string]: boolean | undefined } export type Options = { integrations?: Integrations anonymousId?: ID timestamp?: Date | string context?: AnalyticsContext traits?: object // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any } interface AnalyticsContext { page?: { /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L151} */ path?: string referrer?: string search?: string title?: string url?: string } metrics?: CompactMetric[] /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L285} */ userAgent?: string /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L286-L289} */ locale?: string /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L290-L291} */ library?: { name: string version: string } /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L292-L301} */ traits?: { crossDomainId: string } /** * utm params * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L303-L305} * {@link https://github.com/segmentio/utm-params/blob/master/lib/index.js#L49} */ campaign?: { /** * This can also come from the "utm_campaign" param * * {@link https://github.com/segmentio/utm-params/blob/master/lib/index.js#L40} */ name: string term: string source: string medium: string content: string } /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L415} */ referrer?: { btid?: string urid?: string } /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L322} */ amp?: { id: string } // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any } export interface SegmentEvent { messageId?: string type: 'track' | 'page' | 'identify' | 'group' | 'alias' | 'screen' // page specific category?: string name?: string properties?: object & { [k: string]: JSONValue } // TODO: Narrow types (i.e. only show traits for `track` and `group`) traits?: object & { [k: string]: JSONValue } integrations?: Integrations context?: AnalyticsContext options?: Options userId?: ID anonymousId?: ID groupId?: ID previousId?: ID event?: string /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L284} */ writeKey?: string receivedAt?: Date | string /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L151} */ sentAt?: Date | string /** * {@link https://github.com/segmentio/analytics.js-integrations/blob/2d5c637c022d2661c23449aed237d0d546bf062d/integrations/segmentio/lib/index.js#L311-L320} */ _metadata?: { failedInitializations?: unknown[] bundled?: string[] unbundledIntegrations?: string[] nodeVersion?: string } timestamp?: Date | string }
jbwyme/action-destinations
packages/cli/src/commands/generate/action.ts
import { Command, flags } from '@oclif/command' import chalk from 'chalk' import fs from 'fs-extra' import globby from 'globby' import { camelCase, startCase } from 'lodash' import toTitleCase from 'to-title-case' import ora from 'ora' import path from 'path' import { autoPrompt } from '../../lib/prompt' import { renderTemplates } from '../../lib/templates' import { addKeyToExport } from '../../lib/codemods' import GenerateTypes from './types' export default class GenerateAction extends Command { private spinner: ora.Ora = ora() static description = `Scaffolds a new integration action.` static examples = [ `$ ./bin/run generate:action ACTION <browser|server>`, `$ ./bin/run generate:action postToChannel server --directory=./destinations/slack` ] static flags = { help: flags.help({ char: 'h' }), force: flags.boolean({ char: 'f' }), title: flags.string({ char: 't', description: 'the display name of the action' }), directory: flags.string({ char: 'd', description: 'base directory to scaffold the action' }) } static args = [ { name: 'name', description: 'the action name', required: true }, { name: 'type', description: 'the type of action (browser, server)', required: true } ] async integrationDirs(glob: string) { const integrationDirs = await globby(glob, { expandDirectories: false, onlyDirectories: true, gitignore: true, ignore: ['node_modules'] }) return integrationDirs } parseArgs() { return this.parse(GenerateAction) } async run() { const { args, flags } = this.parseArgs() let integrationsGlob = './packages/destination-actions/src/destinations/*' if ((args.type as string).includes('browser')) { integrationsGlob = './packages/browser-destinations/src/destinations/*' } const integrationDirs = await this.integrationDirs(integrationsGlob) const answers = await autoPrompt(flags, [ { type: 'text', name: 'title', message: 'Action title:', initial: toTitleCase(args.name), format: (val) => toTitleCase(val) }, { type: 'select', name: 'directory', message: 'Which integration (directory)?', choices: integrationDirs.map((integrationPath) => { const [name] = integrationPath.split(path.sep).reverse() return { title: name, value: integrationPath } }) } ]) const slug = camelCase(args.name) const directory = answers.directory || './' const relativePath = path.join(directory, slug) const targetDirectory = path.join(process.cwd(), relativePath) const destinationFolder = path.parse(answers.directory).base const destination = startCase(camelCase(destinationFolder)).replace(/ /g, '') let templatePath = path.join(__dirname, '../../../templates/actions/empty-action') if (args.type === 'browser') { templatePath = path.join(__dirname, '../../../templates/actions/empty-browser-action') } try { this.spinner.start(`Creating ${chalk.bold(args.name)}`) renderTemplates( templatePath, targetDirectory, { name: answers.title, description: '', slug, destination }, flags.force ) this.spinner.succeed(`Scaffold action`) } catch (err) { this.spinner.fail(`Scaffold action: ${chalk.red(err.message)}`) this.exit() } // Update destination with action const entryFile = require.resolve(path.relative(__dirname, path.join(process.cwd(), directory))) try { this.spinner.start(chalk`Updating destination definition`) const destinationStr = fs.readFileSync(entryFile, 'utf8') const exportName = args.type === 'browser' ? 'destination' : 'default' const updatedCode = addKeyToExport(destinationStr, exportName, 'actions', slug) fs.writeFileSync(entryFile, updatedCode, 'utf8') this.spinner.succeed() } catch (err) { this.spinner.fail(chalk`Failed to update your destination imports: ${err.message}`) this.exit() } try { this.spinner.start(chalk`Generating types for {magenta ${slug}} action`) await GenerateTypes.run(['--path', entryFile]) this.spinner.succeed() } catch (err) { this.spinner.fail(chalk`Generating types for {magenta ${slug}} action: ${err.message}`) this.exit() } this.log(chalk.green(`Done creating "${args.name}" 🎉`)) this.log(chalk.green(`Start coding! cd ${targetDirectory}`)) } async catch(error: unknown) { if (this.spinner?.isSpinning) { this.spinner.fail() } throw error } }
jbwyme/action-destinations
packages/destination-subscriptions/src/parse-fql.ts
import { lex, Token, types as TokenType } from '@segment/fql-ts' import { Subscription, Condition, GroupConditionOperator, Operator, ConditionType } from './types' const tokenToConditionType: Record<string, ConditionType> = { type: 'event-type', event: 'event', properties: 'event-property', traits: 'event-trait' } const getTokenValue = (token: Token): string | number | boolean => { if (token.type === 'string') { return token.value.replace(/^"/, '').replace(/"$/, '') } if (token.type === 'number') { return Number(token.value) } if (token.type === 'ident' && ['true', 'false'].includes(token.value)) { return token.value === 'true' } return String(token.value) } const isFqlFunction = (token: Token): boolean => { return token.type === 'ident' && ['contains', 'match'].includes(token.value) } const parseFqlFunction = ( name: string, nodes: Condition[], tokens: Token[], { negate }: { negate: boolean } = { negate: false } ): void => { if (name === 'contains') { // Skip "(" token tokens.shift() const nameToken = tokens.shift() if (!nameToken) { throw new Error('contains() is missing a 1st argument') } // Skip "," token tokens.shift() const valueToken = tokens.shift() if (!valueToken) { throw new Error('contains() is missing a 2nd argument') } // Skip ")" token tokens.shift() if (nameToken.value === 'event') { nodes.push({ type: 'event', operator: negate ? 'not_contains' : 'contains', value: String(getTokenValue(valueToken)) }) } if (/^(properties)/.test(nameToken.value)) { nodes.push({ type: 'event-property', name: nameToken.value.replace(/^(properties)\./, ''), operator: negate ? 'not_contains' : 'contains', value: String(getTokenValue(valueToken)) }) } if (/^(traits)/.test(nameToken.value)) { nodes.push({ type: 'event-trait', name: nameToken.value.replace(/^(traits)\./, ''), operator: negate ? 'not_contains' : 'contains', value: String(getTokenValue(valueToken)) }) } } if (name === 'match') { // Skip "(" token tokens.shift() const nameToken = tokens.shift() if (!nameToken) { throw new Error('match() is missing a 1st argument') } // Skip "," token tokens.shift() const valueToken = tokens.shift() if (!valueToken) { throw new Error('match() is missing a 2nd argument') } // Skip ")" token tokens.shift() let operator: Operator | undefined let value: string | undefined if (valueToken.value.endsWith('*"')) { operator = negate ? 'not_starts_with' : 'starts_with' value = String(getTokenValue(valueToken)).slice(0, -1) } else { operator = negate ? 'not_ends_with' : 'ends_with' value = String(getTokenValue(valueToken)).slice(1) } if (nameToken.value === 'event') { nodes.push({ type: 'event', operator, value }) } if (/^(properties)/.test(nameToken.value)) { nodes.push({ type: 'event-property', name: nameToken.value.replace(/^(properties)\./, ''), operator, value }) } if (/^(traits)/.test(nameToken.value)) { nodes.push({ type: 'event-trait', name: nameToken.value.replace(/^(traits)\./, ''), operator, value }) } } } const parse = (tokens: Token[]): Condition => { const nodes: Condition[] = [] let operator = 'and' let token = tokens.shift() while (token && token.type !== 'eos') { if (token.type === 'ident') { const [tokenStart] = (token.value ?? '').split('.') const conditionType = tokenToConditionType[tokenStart] if (conditionType) { const operatorToken = tokens.shift() if (!operatorToken) { throw new Error('Operator token is missing') } const valueToken = tokens.shift() if (!valueToken) { throw new Error('Value token is missing') } if (conditionType === 'event') { nodes.push({ type: 'event', operator: operatorToken.value as Operator, value: String(getTokenValue(valueToken)) }) } else if (conditionType === 'event-type') { nodes.push({ type: 'event-type', operator: operatorToken.value as Operator, value: String(getTokenValue(valueToken)) }) } else if (conditionType === 'event-property') { if (operatorToken.value === '!=' && valueToken.value === 'null') { nodes.push({ type: 'event-property', name: token.value.replace(/^(properties)\./, ''), operator: 'exists' }) } else if ( operatorToken.value === '=' && valueToken.value === 'null' ) { nodes.push({ type: 'event-property', name: token.value.replace(/^(properties)\./, ''), operator: 'not_exists' }) } else { nodes.push({ type: 'event-property', name: token.value.replace(/^(properties)\./, ''), operator: operatorToken.value as Operator, value: getTokenValue(valueToken) }) } } else if (conditionType === 'event-trait') { if (operatorToken.value === '!=' && valueToken.value === 'null') { nodes.push({ type: 'event-trait', name: token.value.replace(/^(traits)\./, ''), operator: 'exists' }) } else if ( operatorToken.value === '=' && valueToken.value === 'null' ) { nodes.push({ type: 'event-trait', name: token.value.replace(/^(traits)\./, ''), operator: 'not_exists' }) } else { nodes.push({ type: 'event-trait', name: token.value.replace(/^(traits)\./, ''), operator: operatorToken.value as Operator, value: getTokenValue(valueToken) }) } } } if (isFqlFunction(token)) { parseFqlFunction(token.value, nodes, tokens) } } if (token.type === 'operator' && token.value === '!') { if (isFqlFunction(tokens[0])) { const name = tokens[0].value tokens.shift() parseFqlFunction(name, nodes, tokens, { negate: true }) } } if (token.type === 'parenleft') { const groupTokens: Token[] = [] let groupToken = tokens.shift() // eslint-disable-next-line @typescript-eslint/no-non-null-assertion while (groupToken!.type !== 'parenright') { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion groupTokens.push(groupToken!) groupToken = tokens.shift() } groupTokens.push({ type: TokenType.EOS, value: 'eos' }) nodes.push(parse(groupTokens)) } if (token.type === 'conditional') { operator = token.value } token = tokens.shift() } if (nodes.length > 1) { return { type: 'group', operator: operator as GroupConditionOperator, children: nodes } } return nodes[0] } const normalize = (tokens: Token[]): Token[] => { const normalizedTokens: Token[] = [] let index = 0 while (tokens[index]) { if ( tokens[index].type === 'ident' && tokens[index + 1].type === 'dot' && tokens[index + 2].type === 'ident' ) { normalizedTokens.push({ type: TokenType.Ident, value: tokens[index].value + tokens[index + 1].value + tokens[index + 2].value }) index += 3 } else { normalizedTokens.push(tokens[index]) index++ } } return normalizedTokens } const parseFql = (fql: string): Subscription => { try { const ast = parse(normalize(lex(fql).tokens)) if (ast.type !== 'group') { return { type: 'group', operator: 'and', children: [ast] } } return ast } catch (error: unknown) { const err = error instanceof Error ? error : new Error(`Error while parsing ${fql}`) return { error: err } } } export default parseFql
jbwyme/action-destinations
packages/destination-subscriptions/src/validate.ts
import { get } from './get' import { Subscription, Condition, GroupCondition, Operator, ErrorCondition } from './types' const validateGroupCondition = ( condition: GroupCondition, // eslint-disable-next-line @typescript-eslint/no-explicit-any data: any ): boolean => { if (condition.operator === 'and') { return condition.children.every(childCondition => { return validateCondition(childCondition, data) }) } if (condition.operator === 'or') { return condition.children.some(childCondition => { return validateCondition(childCondition, data) }) } return false } // eslint-disable-next-line @typescript-eslint/no-explicit-any const validate = (condition: Subscription, data: any): boolean => { if ((condition as ErrorCondition).error || typeof data === 'undefined') { return false } return validateGroupCondition(condition as GroupCondition, data) } export default validate // eslint-disable-next-line @typescript-eslint/no-explicit-any const validateCondition = (condition: Condition, data: any): boolean => { if (condition.type === 'event-type') { return validateValue(data.type, condition.operator, condition.value) } if (condition.type === 'event') { return validateValue(data.event, condition.operator, condition.value) } if (condition.type === 'event-property') { const properties = ['identify', 'group'].includes(data.type) ? data.traits : data.properties return validateValue( get(properties, condition.name), condition.operator, condition.value ) } if (condition.type === 'event-trait') { const properties = ['identify', 'group'].includes(data.type) ? data.traits : data.properties return validateValue( get(properties, condition.name), condition.operator, condition.value ) } if (condition.type === 'event-context') { return validateValue( get(data.context, condition.name), condition.operator, condition.value ) } if (condition.type === 'group') { return validateGroupCondition(condition, data) } return false } const validateValue = ( actual: unknown, operator: Operator, expected?: string | boolean | number ): boolean => { switch (operator) { case '=': return String(actual) === String(expected) case '!=': return String(actual) !== String(expected) case '<': return Number(actual) < Number(expected) case '<=': return Number(actual) <= Number(expected) case '>': return Number(actual) > Number(expected) case '>=': return Number(actual) >= Number(expected) case 'contains': return typeof actual === 'string' && actual.includes(String(expected)) case 'not_contains': return typeof actual === 'string' && !actual.includes(String(expected)) case 'starts_with': return typeof actual === 'string' && actual.startsWith(String(expected)) case 'not_starts_with': return typeof actual === 'string' && !actual.startsWith(String(expected)) case 'ends_with': return typeof actual === 'string' && actual.endsWith(String(expected)) case 'not_ends_with': return typeof actual === 'string' && !actual.endsWith(String(expected)) case 'exists': return actual !== undefined && actual !== null case 'not_exists': return actual === undefined || actual === null default: return false } }
jbwyme/action-destinations
packages/destination-actions/src/destinations/personas-messaging-twilio/sendSms/generated-types.ts
<filename>packages/destination-actions/src/destinations/personas-messaging-twilio/sendSms/generated-types.ts // Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * User ID in Segment */ userId: string /** * Number to send SMS to when testing */ toNumber?: string /** * Which number to send SMS from */ fromNumber: string /** * Message to send */ body: string }
jbwyme/action-destinations
packages/destination-actions/src/destinations/braze/trackPurchase/index.ts
<filename>packages/destination-actions/src/destinations/braze/trackPurchase/index.ts import { omit, IntegrationError } from '@segment/actions-core' import type { ActionDefinition } from '@segment/actions-core' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' import dayjs from '../../../lib/dayjs' type DateInput = string | Date | number | null | undefined type DateOutput = string | undefined | null function toISO8601(date: DateInput): DateOutput { if (date === null || date === undefined) { return date } const d = dayjs(date) return d.isValid() ? d.toISOString() : undefined } const action: ActionDefinition<Settings, Payload> = { title: 'Track Purchase', description: 'Record purchases in Braze', defaultSubscription: 'event = "Order Completed"', fields: { external_id: { label: 'External User ID', description: 'The unique user identifier', type: 'string', default: { '@path': '$.userId' } }, user_alias: { label: 'User Alias Object', description: 'A user alias object. See [the docs](https://www.braze.com/docs/api/objects_filters/user_alias_object/).', type: 'object', properties: { alias_name: { label: 'Alias Name', type: 'string', required: true }, alias_label: { label: 'Alias Label', type: 'string', required: true } } }, braze_id: { label: 'Braze User Identifier', description: 'The unique user identifier', type: 'string', allowNull: true, default: { '@path': '$.properties.braze_id' } }, time: { label: 'Time', description: 'When the event occurred.', type: 'datetime', required: true, default: { '@path': '$.receivedAt' } }, products: { label: 'Products', description: 'Products purchased', type: 'object', multiple: true, required: true, properties: { product_id: { label: 'Product ID', type: 'string', required: true }, currency: { label: 'Currency', type: 'string' }, price: { label: 'Price', type: 'number', required: true }, quantity: { label: 'Quantity', type: 'integer' } }, default: { '@path': '$.properties.products' } }, properties: { label: 'Event Properties', description: 'Properties of the event', type: 'object', default: { '@path': '$.properties' } }, _update_existing_only: { label: 'Update Existing Only', description: 'Setting this flag to true will put the API in "Update Only" mode. When using a "user_alias", "Update Only" mode is always true.', type: 'boolean', default: false } }, perform: (request, { settings, payload }) => { const { braze_id, user_alias, external_id } = payload if (!braze_id && !user_alias && !external_id) { throw new IntegrationError( 'One of "external_id" or "user_alias" or "braze_id" is required.', 'Missing required fields', 400 ) } // Skip when there are no products to send to Braze if (payload.products.length === 0) { return } const reservedKeys = Object.keys(action.fields.products.properties ?? {}) const properties = omit(payload.properties, reservedKeys) const base = { braze_id, external_id, user_alias, app_id: settings.app_id, time: toISO8601(payload.time), properties, _update_existing_only: payload._update_existing_only } const purchases = payload.products.map((product) => ({ ...base, product_id: product.product_id, currency: product.currency ?? 'USD', price: product.price, quantity: product.quantity })) return request(`${settings.endpoint}/users/track`, { method: 'post', json: { purchases } }) } } export default action
jbwyme/action-destinations
packages/destination-actions/src/destinations/google-analytics-4/generateLead/index.ts
import { ActionDefinition, IntegrationError } from '@segment/actions-core' import { CURRENCY_ISO_CODES } from '../constants' import type { Settings } from '../generated-types' import type { Payload } from './generated-types' const action: ActionDefinition<Settings, Payload> = { title: 'Generate Lead', description: 'Send generate lead events to GA4.', defaultSubscription: 'type = "track"', fields: { client_id: { label: 'Client ID', description: 'Uniquely identifies a user instance of a web client.', type: 'string', required: true, default: { '@if': { exists: { '@path': '$.userId' }, then: { '@path': '$.userId' }, else: { '@path': '$.anonymousId' } } } }, currency: { label: 'Currency', type: 'string', description: 'Currency of the items associated with the event, in 3-letter ISO 4217 format.' }, value: { label: 'Value', type: 'number', description: 'The monetary value of the event.' } }, perform: (request, { payload }) => { if (payload.currency && !CURRENCY_ISO_CODES.includes(payload.currency)) { throw new IntegrationError(`${payload.currency} is not a valid currency code.`, 'Incorrect value format', 400) } // Google requires that currency be included at the event level if value is included. if (payload.value && payload.currency === undefined) { throw new IntegrationError('Currency is required if value is set.', 'Misconfigured required field', 400) } return request('https://www.google-analytics.com/mp/collect', { method: 'POST', json: { client_id: payload.client_id, events: [ { name: 'generate_lead', params: { currency: payload.currency, value: payload.value } } ] } }) } } export default action
jbwyme/action-destinations
packages/core/src/destination-kit/index.ts
<reponame>jbwyme/action-destinations<gh_stars>0 import { validate, parseFql, ErrorCondition } from '@segment/destination-subscriptions' import type { JSONSchema4 } from 'json-schema' import { Action, ActionDefinition, BaseActionDefinition, RequestFn } from './action' import { time, duration } from '../time' import { JSONLikeObject, JSONObject } from '../json-object' import { SegmentEvent } from '../segment-event' import { fieldsToJsonSchema, MinimalInputField } from './fields-to-jsonschema' import createRequestClient, { RequestClient } from '../create-request-client' import { validateSchema } from '../schema-validation' import type { ModifiedResponse } from '../types' import type { GlobalSetting, RequestExtension, ExecuteInput, Result } from './types' import type { AllRequestOptions } from '../request-client' import { IntegrationError, InvalidAuthenticationError } from '../errors' import { AuthTokens, getAuthData, getOAuth2Data, updateOAuthSettings } from './parse-settings' export type { BaseActionDefinition, ActionDefinition, ExecuteInput, RequestFn } export type { MinimalInputField } export { fieldsToJsonSchema } const RETRY_ATTEMPTS = 2 const OAUTH2_SCHEME = 'oauth2' export interface SubscriptionStats { duration: number destination: string action: string subscribe: string state: string input: JSONLikeObject output: Result[] | null } interface PartnerActions<Settings, Payload extends JSONLikeObject> { [key: string]: Action<Settings, Payload> } export interface BaseDefinition { /** The name of the destination */ name: string /** * The mode of the destination * 'cloud' mode is made up of actions that run server-side, but can also have device-mode enrichment actions * 'device' mode is made up of actions that run in the browser */ mode: 'cloud' | 'device' /** A human-friendly description of the destination */ description?: string /** * The url-friendly unique slug for the destination * When provided, the `register` command will use this slug * instead of generating one from the `name` */ slug?: string /** Actions */ actions: Record<string, BaseActionDefinition> /** Subscription presets automatically applied in quick setup */ presets?: Subscription[] } export interface DestinationDefinition<Settings = unknown> extends BaseDefinition { mode: 'cloud' /** Actions */ actions: Record<string, ActionDefinition<Settings>> /** An optional function to extend requests sent from the destination (including all actions) */ extendRequest?: RequestExtension<Settings> /** Optional authentication configuration */ authentication?: AuthenticationScheme<Settings> } export interface Subscription { name?: string partnerAction: string subscribe: string mapping?: JSONObject } export interface OAuth2ClientCredentials extends AuthTokens { /** Publicly exposed string that is used by the partner API to identify the application, also used to build authorization URLs that are presented to users */ clientId: string /** Used to authenticate the identity of the application to the partner API when the application requests to access a user’s account, must be kept private between the application and the API. */ clientSecret: string } export interface RefreshAccessTokenResult { /** OAuth2 access token that was recently acquired */ accessToken: string /** Provide in case the partner API also updates the refresh token when requesting a fresh access token */ refreshToken?: string } interface AuthSettings<Settings> { settings: Settings auth: AuthTokens } interface RefreshAuthSettings<Settings> { settings: Settings auth: OAuth2ClientCredentials } interface Authentication<Settings> { /** The authentication scheme */ scheme: 'basic' | 'custom' | 'oauth2' /** The fields related to authentication */ fields: Record<string, GlobalSetting> /** A function that validates the user's authentication inputs. It is highly encouraged to define this whenever possible. */ testAuthentication?: (request: RequestClient, input: AuthSettings<Settings>) => Promise<unknown> | unknown } /** * Custom authentication scheme * Typically used for "API Key" authentication. */ export interface CustomAuthentication<Settings> extends Authentication<Settings> { scheme: 'custom' } /** * Basic authentication scheme * @see {@link https://datatracker.ietf.org/doc/html/rfc7617} */ export interface BasicAuthentication<Settings> extends Authentication<Settings> { scheme: 'basic' } /** * OAuth2 authentication scheme */ export interface OAuth2Authentication<Settings> extends Authentication<Settings> { scheme: 'oauth2' /** A function that is used to refresh the access token * @todo look into merging input and oauthConfig so we can keep all the request functions with the same method signature (2 arguments) */ refreshAccessToken?: ( request: RequestClient, input: RefreshAuthSettings<Settings> ) => Promise<RefreshAccessTokenResult> } // eslint-disable-next-line @typescript-eslint/no-explicit-any export type AuthenticationScheme<Settings = any> = | BasicAuthentication<Settings> | CustomAuthentication<Settings> | OAuth2Authentication<Settings> interface EventInput<Settings> { readonly event: SegmentEvent readonly mapping: JSONObject readonly settings: Settings /** Authentication-related data based on the destination's authentication.fields definition and authentication scheme */ readonly auth?: AuthTokens } export interface DecoratedResponse extends ModifiedResponse { request: Request options: AllRequestOptions } export class Destination<Settings = JSONObject> { readonly definition: DestinationDefinition<Settings> readonly name: string readonly authentication?: AuthenticationScheme<Settings> readonly extendRequest?: RequestExtension<Settings> // eslint-disable-next-line @typescript-eslint/no-explicit-any readonly actions: PartnerActions<Settings, any> readonly responses: DecoratedResponse[] readonly settingsSchema?: JSONSchema4 constructor(destination: DestinationDefinition<Settings>) { this.definition = destination this.name = destination.name this.extendRequest = destination.extendRequest this.actions = {} this.authentication = destination.authentication this.responses = [] // Convert to complete JSON Schema if (this.authentication?.fields) { this.settingsSchema = fieldsToJsonSchema(this.authentication.fields) } for (const action of Object.keys(destination.actions)) { this.partnerAction(action, destination.actions[action]) } } async testAuthentication(settings: Settings): Promise<void> { const destinationSettings = this.getDestinationSettings(settings as unknown as JSONObject) const auth = getAuthData(settings as unknown as JSONObject) const data = { settings: destinationSettings, auth } const context: ExecuteInput<Settings, {}> = { settings: destinationSettings, payload: {}, auth } if (this.settingsSchema) { validateSchema(settings, this.settingsSchema, `${this.name}:settings`) } if (!this.authentication?.testAuthentication) { return } const options = this.extendRequest?.(context) ?? {} const requestClient = createRequestClient(options) try { await this.authentication.testAuthentication(requestClient, data) } catch (error) { throw new Error('Credentials are invalid') } } refreshAccessToken( settings: Settings, oauthData: OAuth2ClientCredentials ): Promise<RefreshAccessTokenResult> | undefined { if (this.authentication?.scheme !== OAUTH2_SCHEME) { throw new IntegrationError( 'refreshAccessToken is only valid with oauth2 authentication scheme', 'NotImplemented', 501 ) } // TODO: clean up context/extendRequest so we don't have to send information that is not needed (payload & cachedFields) const context: ExecuteInput<Settings, {}> = { settings, payload: {}, auth: getAuthData(settings as unknown as JSONObject) } const options = this.extendRequest?.(context) ?? {} const requestClient = createRequestClient(options) if (!this.authentication?.refreshAccessToken) { return undefined } return this.authentication.refreshAccessToken(requestClient, { settings, auth: oauthData }) } private partnerAction(slug: string, definition: ActionDefinition<Settings>): Destination<Settings> { const action = new Action<Settings, {}>(this.name, definition, this.extendRequest) action.on('response', (response) => { if (response) { this.responses.push(response) } }) this.actions[slug] = action return this } protected executeAction( actionSlug: string, { event, mapping, settings, auth }: EventInput<Settings> ): Promise<Result[]> { const action = this.actions[actionSlug] if (!action) { return Promise.resolve([]) } return action.execute({ mapping, data: event, settings, auth }) } private async onSubscription( subscription: Subscription, event: SegmentEvent, settings: Settings, auth: AuthTokens, onComplete?: (stats: SubscriptionStats) => void ): Promise<Result[]> { const subscriptionStartedAt = time() const actionSlug = subscription.partnerAction const input = { event, mapping: subscription.mapping || {}, settings, auth } let state = 'pending' let results: Result[] | null = null try { if (!subscription.subscribe || typeof subscription.subscribe !== 'string') { state = 'skipped' results = [{ output: 'invalid subscription' }] return results } const parsedSubscription = parseFql(subscription.subscribe) if ((parsedSubscription as ErrorCondition).error) { state = 'skipped' results = [{ output: `invalid subscription : ${(parsedSubscription as ErrorCondition).error.message}` }] return results } const isSubscribed = validate(parsedSubscription, event) if (!isSubscribed) { state = 'skipped' results = [{ output: 'not subscribed' }] return results } results = await this.executeAction(actionSlug, input) state = 'done' return results } catch (error) { state = 'errored' results = [{ error }] if (error.name === 'AggregateAjvError' || error.name === 'ValidationError') { error.status = 400 } throw error } finally { const subscriptionEndedAt = time() const subscriptionDuration = duration(subscriptionStartedAt, subscriptionEndedAt) onComplete?.({ duration: subscriptionDuration, destination: this.name, action: actionSlug, subscribe: subscription.subscribe, state, input: { event: input.event as unknown as JSONLikeObject, mapping: input.mapping, settings: input.settings as unknown as JSONLikeObject }, output: results }) } } /** * Note: Until we move subscriptions upstream (into int-consumer) we've opted * to have failures abort the set of subscriptions and get potentially retried by centrifuge */ public async onEvent( event: SegmentEvent, settings: JSONObject, options?: { onTokenRefresh?: (tokens: RefreshAccessTokenResult) => void onComplete?: (stats: SubscriptionStats) => void } ): Promise<Result[]> { for (let i = 0; i < RETRY_ATTEMPTS; i++) { try { return await this.onEventInternal(event, settings, options?.onComplete) } catch (error) { const statusCode = error?.status ?? error?.response?.status ?? 500 // Throw original error if it is unrelated to invalid access tokens and not an oauth2 scheme if (!(statusCode === 401 && this.authentication?.scheme === OAUTH2_SCHEME)) { throw error } const destinationSettings = this.getDestinationSettings(settings) const oauthSettings = getOAuth2Data(settings) const newTokens = await this.refreshAccessToken(destinationSettings, oauthSettings) if (!newTokens) { throw new InvalidAuthenticationError('Failed to refresh access token') } settings = updateOAuthSettings(settings, newTokens) options?.onTokenRefresh?.(newTokens) } } throw new InvalidAuthenticationError() } private async onEventInternal( event: SegmentEvent, settings: JSONObject, onComplete?: (stats: SubscriptionStats) => void ): Promise<Result[]> { const subscriptions = this.getSubscriptions(settings) const destinationSettings = this.getDestinationSettings(settings) const authData = getAuthData(settings) const promises = subscriptions.map((subscription) => this.onSubscription(subscription, event, destinationSettings, authData, onComplete) ) const results = await Promise.all(promises) return ([] as Result[]).concat(...results) } private getSubscriptions(settings: JSONObject): Subscription[] { // Support receiving: // - a single subscription (e.g. via a Centrifuge job) // - a list of subscriptions (e.g. via Event Tester or local testing) const { subscription, subscriptions } = settings let parsedSubscriptions: unknown if (subscription) { parsedSubscriptions = [subscription] } else if (Array.isArray(subscriptions)) { parsedSubscriptions = subscriptions } else { parsedSubscriptions = [] } return parsedSubscriptions as Subscription[] } private getDestinationSettings(settings: JSONObject): Settings { const { subcription, subscriptions, oauth, ...otherSettings } = settings return otherSettings as unknown as Settings } }
jbwyme/action-destinations
packages/browser-destinations/src/destinations/fullstory/index.ts
import * as FullStory from '@fullstory/browser' import type { BrowserDestinationDefinition } from '../../lib/browser-destinations' import { browserDestination } from '../../runtime/shim' import event from './event' import type { Settings } from './generated-types' import { initScript } from './init-script' import setUserVars from './setUserVars' export const destination: BrowserDestinationDefinition<Settings, typeof FullStory> = { name: 'Fullstory', mode: 'device', settings: { orgId: { description: 'The organization ID for FullStory', label: 'orgId', type: 'string', required: true } }, actions: { event, setUserVars }, initialize: async ({ settings }, dependencies) => { initScript({ debug: false, org: settings.orgId }) await dependencies.loadScript('https://edge.fullstory.com/s/fs.js') await dependencies.resolveWhen(() => Object.prototype.hasOwnProperty.call(window, 'FS'), 100) return FullStory } } export default browserDestination(destination)
jbwyme/action-destinations
packages/destination-actions/src/destinations/customerio/triggerCampaign/generated-types.ts
// Generated file. DO NOT MODIFY IT BY HAND. export interface Payload { /** * ID of the campaign to trigger. */ id: number /** * Custom Liquid merge data to include with the trigger. */ data?: { [k: string]: unknown } /** * Additional recipient conditions to filter recipients. If this is used, "IDs" may not be used. */ recipients?: { [k: string]: unknown } /** * List of profile IDs to use as campaign recipients. If this is used, "Recipients" may not be used. */ ids?: string[] }
mathieueveillard/temp
src/index.spec.ts
namespace Ko { test("Can you make spareMoney idempotent?", function () { interface AbstractEvent<T extends string, P> { id: string; type: T; payload: P; } type MoneySparedEvent = AbstractEvent<"MONEY_SPARED_EVENT", number>; type MoneyWithdrawnEvent = AbstractEvent<"MONEY_WITHDRAWN_EVENT", number>; type Event = MoneySparedEvent | MoneyWithdrawnEvent; interface Wealth { readonly value: number; } const wealthReducer = (wealth: Wealth) => (additionalAmount: number): Wealth => { return { ...wealth, value: wealth.value + additionalAmount, }; }; const pastEvents = new Set<string>(); // A database emulation let wealth: Wealth = { value: 0, }; function spareMoney({ id, type, payload: additionalAmount }: Event): void { if (type !== "MONEY_SPARED_EVENT" || pastEvents.has(id)) { return; } wealth = wealthReducer(wealth)(additionalAmount); pastEvents.add(id); } const event: MoneySparedEvent = { id: "b87a6147-9c6e-4cff-bb40-819ccea42c56", type: "MONEY_SPARED_EVENT", payload: 450, }; spareMoney(event); expect(wealth.value).toEqual(450); spareMoney(event); expect(wealth.value).toEqual(450); // Your job: make the test pass! }); }
ChelesteWang/umi-next
packages/preset-umi/src/features/transform/transform.ts
<reponame>ChelesteWang/umi-next import * as Babel from '@umijs/bundler-utils/compiled/babel/core'; import * as t from '@umijs/bundler-utils/compiled/babel/types'; import { winPath } from '@umijs/utils'; import { join } from 'path'; import { IApi } from '../../types'; export default (api: IApi) => { api.addBeforeBabelPresets(() => { return [ { plugins: [ () => { return { pre() { // @ts-ignore this.cache = new Map<string, any>(); }, post(state: any) { // @ts-ignore const { cache } = this; const filename = winPath(state.opts.filename); if ( cache.has(filename) && !filename.includes('bundler-webpack/client') && !filename.startsWith(winPath(join(api.cwd, 'node_modules'))) ) { api.applyPlugins({ key: 'onCheckCode', args: { ...cache.get(state.opts.filename), file: state.opts.filename, isFromTmp: state.opts.filename.startsWith( api.paths.absTmpPath, ), }, }); } }, visitor: { Program: { enter(path: Babel.NodePath<t.Program>) { // @ts-ignore const file = path?.hub.file.opts.filename; // @ts-ignore const cache = this.cache; // reset cache cache.set(file, { code: path.hub.getCode(), imports: [], }); path.node.body.forEach((node) => { // import x from 'x'; { default: 'x' } // import * as x2 from 'x'; { namespace: 'x2' } // import x3, * as xx from 'x'; { default: 'x3', namespace: 'xx' } // import { x4, a as b } from 'x'; { specifiers: { x4: 'x4', a: 'b' } } if (t.isImportDeclaration(node)) { const ret: Record<string, any> = { source: node.source.value, loc: node.loc, }; node.specifiers.forEach((specifier) => { if (t.isImportDefaultSpecifier(specifier)) { ret.default = specifier.local.name; } else if (t.isImportNamespaceSpecifier(specifier)) { ret.namespace = specifier.local.name; } else if (t.isImportSpecifier(specifier)) { ret.specifiers ||= {}; ret.specifiers[ t.isIdentifier(specifier.imported) ? specifier.imported.name : specifier.imported.value ] = specifier.local.name; } }); cache.get(file).imports.push(ret); } // TODO: // exports // callExpression // newExpression }); }, }, }, }; }, ], }, ]; }); };
ChelesteWang/umi-next
packages/preset-umi/src/features/configPlugins/schema.ts
import type { Root } from '@umijs/core/compiled/@hapi/joi'; import { NpmClientEnum } from '@umijs/utils'; export function getSchemas(): Record<string, (Joi: Root) => any> { return { plugins: (Joi) => Joi.array().items(Joi.string()), favicon: (Joi) => Joi.string(), headScripts: (Joi) => Joi.array().items(Joi.alternatives(Joi.string())), scripts: (Joi) => Joi.array().items(Joi.alternatives(Joi.string())), npmClient: (Joi) => Joi.string().valid( NpmClientEnum.pnpm, NpmClientEnum.tnpm, NpmClientEnum.cnpm, NpmClientEnum.yarn, NpmClientEnum.npm, ), }; }
ChelesteWang/umi-next
packages/umi/index.d.ts
export * from '@umijs/renderer-react'; export type { IApi } from '../preset-umi'; export * from './dist/index';
snowlotus530/threejs_fiber_react
example/src/demos/ContextMenuOverride.tsx
import React, { useState } from 'react' import { Canvas } from '@react-three/fiber' export default function App() { const [state, set] = useState(false) return ( <Canvas orthographic camera={{ zoom: 150, fov: 75, position: [0, 0, 25] }}> <ambientLight /> <pointLight position={[10, 10, 10]} /> <mesh position={[0, 0, 0]} onContextMenu={(ev) => { ev.nativeEvent.preventDefault() set((value) => !value) }}> <boxBufferGeometry args={[1, 1, 1]} /> <meshPhysicalMaterial color={state ? 'hotpink' : 'blue'} /> </mesh> </Canvas> ) }
snowlotus530/threejs_fiber_react
packages/fiber/src/web/index.tsx
<filename>packages/fiber/src/web/index.tsx import * as THREE from 'three' import * as React from 'react' import { RootTag } from 'react-reconciler' import { UseStore } from 'zustand' import { is } from '../core/is' import { createStore, StoreProps, isRenderer, context, RootState, Size } from '../core/store' import { createRenderer, extend, prepare, Root } from '../core/renderer' import { createLoop, addEffect, addAfterEffect, addTail } from '../core/loop' import { createPointerEvents as events } from './events' import { Canvas } from './Canvas' import { EventManager } from '../core/events' const roots = new Map<Element, Root>() const modes = ['legacy', 'blocking', 'concurrent'] as const const { invalidate, advance } = createLoop(roots) const { reconciler, applyProps } = createRenderer(roots) export type RenderProps<TCanvas extends Element> = Omit<StoreProps, 'gl' | 'events' | 'size'> & { gl?: THREE.WebGLRenderer | Partial<THREE.WebGLRendererParameters> events?: (store: UseStore<RootState>) => EventManager<TCanvas> size?: Size mode?: typeof modes[number] onCreated?: (state: RootState) => void } const createRendererInstance = <TElement extends Element>( gl: THREE.WebGLRenderer | Partial<THREE.WebGLRendererParameters> | undefined, canvas: TElement, ): THREE.WebGLRenderer => isRenderer(gl as THREE.WebGLRenderer) ? (gl as THREE.WebGLRenderer) : new THREE.WebGLRenderer({ powerPreference: 'high-performance', canvas: canvas as unknown as HTMLCanvasElement, antialias: true, alpha: true, ...gl, }) function render<TCanvas extends Element>( element: React.ReactNode, canvas: TCanvas, { gl, size, mode = modes[1], events, onCreated, ...props }: RenderProps<TCanvas> = {}, ): UseStore<RootState> { // Allow size to take on container bounds initially if (!size) { size = { width: canvas.parentElement?.clientWidth ?? 0, height: canvas.parentElement?.clientHeight ?? 0, } } let root = roots.get(canvas) let fiber = root?.fiber let store = root?.store let state = store?.getState() if (fiber && state) { const lastProps = state.internal.lastProps // When a root was found, see if any fundamental props must be changed or exchanged // Check pixelratio if (props.dpr !== undefined && !is.equ(lastProps.dpr, props.dpr)) state.setDpr(props.dpr) // Check size if (!is.equ(lastProps.size, size)) state.setSize(size.width, size.height) // For some props we want to reset the entire root // Changes to the color-space const linearChanged = props.linear !== lastProps.linear if (linearChanged) { unmountComponentAtNode(canvas) fiber = undefined } } if (!fiber) { // If no root has been found, make one // Create gl const glRenderer = createRendererInstance(gl, canvas) // Enable VR if requested if (props.vr) { glRenderer.xr.enabled = true glRenderer.setAnimationLoop((timestamp) => advance(timestamp, true)) } // Create store store = createStore(applyProps, invalidate, advance, { gl: glRenderer, size, ...props }) const state = store.getState() // Create renderer fiber = reconciler.createContainer(store, modes.indexOf(mode) as RootTag, false, null) // Map it roots.set(canvas, { fiber, store }) // Store events internally if (events) state.set({ events: events(store) }) } if (store && fiber) { reconciler.updateContainer( <Provider store={store} element={element} onCreated={onCreated} target={canvas} />, fiber, null, () => undefined, ) return store } else { throw 'Error creating root!' } } function Provider<TElement extends Element>({ store, element, onCreated, target, }: { onCreated?: (state: RootState) => void store: UseStore<RootState> element: React.ReactNode target: TElement }) { React.useEffect(() => { const state = store.getState() // Flag the canvas active, rendering will now begin state.set((state) => ({ internal: { ...state.internal, active: true } })) // Connect events state.events.connect?.(target) // Notifiy that init is completed, the scene graph exists, but nothing has yet rendered if (onCreated) onCreated(state) }, []) return <context.Provider value={store}>{element}</context.Provider> } function unmountComponentAtNode<TElement extends Element>(canvas: TElement, callback?: (canvas: TElement) => void) { const root = roots.get(canvas) const fiber = root?.fiber if (fiber) { const state = root?.store.getState() if (state) state.internal.active = false reconciler.updateContainer(null, fiber, null, () => { if (state) { setTimeout(() => { state.events.disconnect?.() state.gl?.renderLists?.dispose?.() state.gl?.forceContextLoss?.() dispose(state) roots.delete(canvas) if (callback) callback(canvas) }, 500) } }) } } function dispose<TObj extends { dispose?: () => void; type?: string; [key: string]: any }>(obj: TObj) { if (obj.dispose && obj.type !== 'Scene') obj.dispose() for (const p in obj) { ;(p as any).dispose?.() delete obj[p] } } const act = reconciler.act const hasSymbol = is.fun(Symbol) && Symbol.for const REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca function createPortal( children: React.ReactNode, container: THREE.Object3D, implementation?: any, key: any = null, ): React.ReactNode { return { $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children, containerInfo: prepare(container), implementation, } } reconciler.injectIntoDevTools({ bundleType: process.env.NODE_ENV === 'production' ? 0 : 1, rendererPackageName: '@react-three/fiber', version: '17.0.2', }) export * from '../core/hooks' export { context, render, unmountComponentAtNode, createPortal, events, reconciler, applyProps, dispose, invalidate, advance, extend, addEffect, addAfterEffect, addTail, Canvas, act, roots as _roots, }
snowlotus530/threejs_fiber_react
packages/fiber/src/web/Canvas.tsx
<gh_stars>1-10 import * as React from 'react' import mergeRefs from 'react-merge-refs' import useMeasure, { Options as ResizeOptions } from 'react-use-measure' import { render, unmountComponentAtNode, RenderProps } from './index' import { createPointerEvents } from './events' import { UseStore } from 'zustand' import { RootState } from '../core/store' import { EventManager } from '../core/events' export interface Props extends Omit<RenderProps<HTMLCanvasElement>, 'size' | 'events'>, React.HTMLAttributes<HTMLDivElement> { children: React.ReactNode fallback?: React.ReactNode resize?: ResizeOptions events?: (store: UseStore<RootState>) => EventManager<any> } type SetBlock = false | Promise<null> | null type UnblockProps = { set: React.Dispatch<React.SetStateAction<SetBlock>>; children: React.ReactNode } // React currently throws a warning when using useLayoutEffect on the server. // To get around it, we can conditionally useEffect on the server (no-op) and // useLayoutEffect in the browser. const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect function Block({ set }: Omit<UnblockProps, 'children'>) { useIsomorphicLayoutEffect(() => { set(new Promise(() => null)) return () => set(false) }, []) return null } class ErrorBoundary extends React.Component<{ set: React.Dispatch<any> }, { error: boolean }> { state = { error: false } static getDerivedStateFromError = () => ({ error: true }) componentDidCatch(error: any) { this.props.set(error) } render() { return this.state.error ? null : this.props.children } } export const Canvas = React.forwardRef<HTMLCanvasElement, Props>(function Canvas( { children, fallback, tabIndex, resize, id, style, className, events, ...props }, forwardedRef, ) { const [containerRef, size] = useMeasure({ scroll: true, debounce: { scroll: 50, resize: 0 }, ...resize }) const canvasRef = React.useRef<HTMLCanvasElement>(null!) const [block, setBlock] = React.useState<SetBlock>(false) const [error, setError] = React.useState<any>(false) // Suspend this component if block is a promise (2nd run) if (block) throw block // Throw exception outwards if anything within canvas throws if (error) throw error // Execute JSX in the reconciler as a layout-effect useIsomorphicLayoutEffect(() => { if (size.width > 0 && size.height > 0) { render( <ErrorBoundary set={setError}> <React.Suspense fallback={<Block set={setBlock} />}>{children}</React.Suspense> </ErrorBoundary>, canvasRef.current, { ...props, size, events: events || createPointerEvents }, ) } }, [size, children]) useIsomorphicLayoutEffect(() => { const container = canvasRef.current return () => unmountComponentAtNode(container) }, []) return ( <div ref={containerRef} id={id} className={className} tabIndex={tabIndex} style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', ...style }}> <canvas ref={mergeRefs([canvasRef, forwardedRef])} style={{ display: 'block' }}> {fallback} </canvas> </div> ) })
snowlotus530/threejs_fiber_react
packages/fiber/src/web/events.ts
import { UseStore } from 'zustand' import { RootState } from '../core/store' import type { EventManager, Events } from '../core/events' import { createEvents } from '../core/events' export function createPointerEvents(store: UseStore<RootState>): EventManager<HTMLElement> { const { handlePointer } = createEvents(store) const names = { onClick: ['click', false], onContextMenu: ['contextmenu', false], onDoubleClick: ['dblclick', false], onWheel: ['wheel', true], onPointerDown: ['pointerdown', true], onPointerUp: ['pointerup', true], onPointerLeave: ['pointerleave', true], onPointerMove: ['pointermove', true], onPointerCancel: ['pointercancel', true], onLostPointerCapture: ['lostpointercapture', true], } as const return { connected: false, handlers: Object.keys(names).reduce((acc, key) => ({ ...acc, [key]: handlePointer(key) }), {}) as unknown as Events, connect: (target: HTMLElement) => { const { set, events } = store.getState() events.disconnect?.() set((state) => ({ events: { ...state.events, connected: target } })) Object.entries(events?.handlers ?? []).forEach(([name, event]) => { const [eventName, passive] = names[name as keyof typeof names] target.addEventListener(eventName, event, { passive }) }) }, disconnect: () => { const { set, events } = store.getState() if (events.connected) { Object.entries(events.handlers ?? []).forEach(([name, event]) => { if (events && events.connected instanceof HTMLElement) { const [eventName] = names[name as keyof typeof names] events.connected.removeEventListener(eventName, event) } }) set((state) => ({ events: { ...state.events, connected: false } })) } }, } }
snowlotus530/threejs_fiber_react
packages/fiber/tests/web/web.core.test.tsx
jest.mock('scheduler', () => require('scheduler/unstable_mock')) import * as React from 'react' import { Color, Group, Camera, Scene, Mesh, BoxBufferGeometry, MeshBasicMaterial, MeshStandardMaterial, PCFSoftShadowMap, ACESFilmicToneMapping, sRGBEncoding, Object3D, } from 'three' import { createCanvas } from '@react-three/test-renderer/src/createTestCanvas' import { createWebGLContext } from '@react-three/test-renderer/src/createWebGLContext' import { render, act, unmountComponentAtNode, extend } from '../../src/web/index' import { UseStore } from 'zustand' import { RootState } from '../../src/core/store' import { ReactThreeFiber } from '../../src' type ComponentMesh = Mesh<BoxBufferGeometry, MeshBasicMaterial> /* This class is used for one of the tests */ class HasObject3dMember extends Object3D { public attachment?: Object3D = undefined } /* This class is used for one of the tests */ class HasObject3dMethods extends Object3D { attachedObj3d?: Object3D detachedObj3d?: Object3D customAttach(obj3d: Object3D) { this.attachedObj3d = obj3d } detach(obj3d: Object3D) { this.detachedObj3d = obj3d } } extend({ HasObject3dMember, HasObject3dMethods }) declare global { namespace JSX { interface IntrinsicElements { hasObject3dMember: ReactThreeFiber.Node<HasObject3dMember, typeof HasObject3dMember> hasObject3dMethods: ReactThreeFiber.Node<HasObject3dMethods, typeof HasObject3dMethods> } } } beforeAll(() => { Object.defineProperty(window, 'devicePixelRatio', { configurable: true, value: 2, }) }) describe('web core', () => { let canvas: HTMLCanvasElement = null! beforeEach(() => { canvas = createCanvas({ beforeReturn: (canvas) => { //@ts-ignore canvas.getContext = (type: string) => { if (type === 'webgl' || type === 'webgl2') { return createWebGLContext(canvas) } } }, }) }) it('renders a simple component', async () => { const Mesh = () => { return ( <mesh> <boxBufferGeometry args={[2, 2]} /> <meshBasicMaterial /> </mesh> ) } let scene: Scene = null! await act(async () => { scene = render(<Mesh />, canvas).getState().scene }) expect(scene.children[0].type).toEqual('Mesh') }) it('renders an empty scene', async () => { const Empty = () => null let scene: Scene = null! await act(async () => { scene = render(<Empty />, canvas).getState().scene }) expect(scene.type).toEqual('Scene') expect(scene.children).toEqual([]) }) it('can render a composite component', async () => { class Parent extends React.Component { render() { return ( <group> <color attach="background" args={[0, 0, 0]} /> <Child /> </group> ) } } const Child = () => { return ( <mesh> <boxBufferGeometry args={[2, 2]} /> <meshBasicMaterial /> </mesh> ) } let scene: Scene = null! await act(async () => { scene = render(<Parent />, canvas).getState().scene }) expect(scene.children[0].type).toEqual('Group') // @ts-expect-error we do append background to group, but it's not wrong because it won't do anything. expect((scene.children[0] as Group).background.getStyle()).toEqual('rgb(0,0,0)') expect(scene.children[0].children[0].type).toEqual('Mesh') expect((scene.children[0].children[0] as ComponentMesh).geometry.type).toEqual('BoxGeometry') expect((scene.children[0].children[0] as ComponentMesh).material.type).toEqual('MeshBasicMaterial') }) it('renders some basics with an update', async () => { let renders = 0 class Component extends React.PureComponent { state = { pos: 3 } componentDidMount() { this.setState({ pos: 7 }) } render() { renders++ return ( <group position-x={this.state.pos}> <Child /> <Null /> </group> ) } } const Child = () => { renders++ return <color attach="background" args={[0, 0, 0]} /> } const Null = () => { renders++ return null } let scene: Scene = null! await act(async () => { scene = render(<Component />, canvas).getState().scene }) expect(scene.children[0].position.x).toEqual(7) expect(renders).toBe(12) }) it('updates types & names', async () => { let scene: Scene = null! await act(async () => { scene = render( <mesh> <meshBasicMaterial name="basicMat"> <color attach="color" args={[0, 0, 0]} /> </meshBasicMaterial> </mesh>, canvas, ).getState().scene }) expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, MeshBasicMaterial>).material.type).toEqual( 'MeshBasicMaterial', ) expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, MeshBasicMaterial>).material.name).toEqual('basicMat') await act(async () => { scene = render( <mesh> <meshStandardMaterial name="standardMat"> <color attach="color" args={[255, 255, 255]} /> </meshStandardMaterial> </mesh>, canvas, ).getState().scene }) expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, MeshStandardMaterial>).material.type).toEqual( 'MeshStandardMaterial', ) expect((scene.children[0] as THREE.Mesh<THREE.BoxGeometry, MeshStandardMaterial>).material.name).toEqual( 'standardMat', ) }) it('attaches Object3D children that use attach', async () => { let scene: Scene = null! await act(async () => { scene = render( <hasObject3dMember> <mesh attach="attachment" /> </hasObject3dMember>, canvas, ).getState().scene }) const attachedMesh = (scene.children[0] as HasObject3dMember).attachment expect(attachedMesh).toBeDefined() expect(attachedMesh?.type).toBe('Mesh') // attaching is *instead of* being a regular child expect(scene.children[0].children.length).toBe(0) }) describe('attaches Object3D children that use attachFns', () => { it('attachFns as strings', async () => { let scene: Scene = null! await act(async () => { scene = render( <hasObject3dMethods> <mesh attachFns={['customAttach', 'detach']} /> </hasObject3dMethods>, canvas, ).getState().scene }) const attachedMesh = (scene.children[0] as HasObject3dMethods).attachedObj3d expect(attachedMesh).toBeDefined() expect(attachedMesh?.type).toBe('Mesh') // attaching is *instead of* being a regular child expect(scene.children[0].children.length).toBe(0) // and now detach .. expect((scene.children[0] as HasObject3dMethods).detachedObj3d).toBeUndefined() await act(async () => { render(<hasObject3dMethods />, canvas) }) const detachedMesh = (scene.children[0] as HasObject3dMethods).detachedObj3d expect(detachedMesh).toBe(attachedMesh) }) it('attachFns as functions', async () => { let scene: Scene = null! let attachedMesh: Mesh = null! let detachedMesh: Mesh = null! await act(async () => { scene = render( <hasObject3dMethods> <mesh attachFns={[ (mesh: Mesh, parentInstance: HasObject3dMethods) => { attachedMesh = mesh }, (mesh: Mesh, parentInstance: HasObject3dMethods) => { detachedMesh = mesh }, ]} /> </hasObject3dMethods>, canvas, ).getState().scene }) expect(attachedMesh).toBeDefined() expect(attachedMesh?.type).toBe('Mesh') // attaching is *instead of* being a regular child expect(scene.children[0].children.length).toBe(0) await act(async () => { render(<hasObject3dMethods />, canvas) }) expect(detachedMesh).toBe(attachedMesh) }) }) it('does the full lifecycle', async () => { const log: string[] = [] class Log extends React.Component<{ name: string }> { render() { log.push('render ' + this.props.name) return <group /> } componentDidMount() { log.push('mount ' + this.props.name) } componentWillUnmount() { log.push('unmount ' + this.props.name) } } await act(async () => { render(<Log key="foo" name="Foo" />, canvas) }) await act(async () => { unmountComponentAtNode(canvas) }) expect(log).toEqual(['render Foo', 'render Foo', 'mount Foo', 'unmount Foo']) }) it('will make an Orthographic Camera & set the position', async () => { let camera: Camera = null! await act(async () => { camera = render(<group />, canvas, { orthographic: true, camera: { position: [0, 0, 5] } }).getState().camera }) expect(camera.type).toEqual('OrthographicCamera') expect(camera.position.z).toEqual(5) }) it('should handle an performance changing functions', async () => { let state: UseStore<RootState> = null! await act(async () => { state = render(<group />, canvas, { dpr: [1, 2], performance: { min: 0.2 }, }) }) expect(state.getState().viewport.initialDpr).toEqual(2) expect(state.getState().performance.min).toEqual(0.2) expect(state.getState().performance.current).toEqual(1) await act(async () => { state.getState().setDpr(0.1) }) expect(state.getState().viewport.dpr).toEqual(0.1) jest.useFakeTimers() await act(async () => { state.getState().performance.regress() jest.advanceTimersByTime(100) }) expect(state.getState().performance.current).toEqual(0.2) await act(async () => { jest.advanceTimersByTime(200) }) expect(state.getState().performance.current).toEqual(1) jest.useRealTimers() }) it('should set PCFSoftShadowMap as the default shadow map', async () => { let state: UseStore<RootState> = null! await act(async () => { state = render(<group />, canvas, { shadows: true, }) }) expect(state.getState().gl.shadowMap.type).toBe(PCFSoftShadowMap) }) it('should set tonemapping to ACESFilmicToneMapping and outputEncoding to sRGBEncoding if linear is false', async () => { let state: UseStore<RootState> = null! await act(async () => { state = render(<group />, canvas, { linear: false, }) }) expect(state.getState().gl.toneMapping).toBe(ACESFilmicToneMapping) expect(state.getState().gl.outputEncoding).toBe(sRGBEncoding) }) it('will render components that are extended', async () => { class MyColor extends Color { constructor(col: number) { super(col) } } await expect(async () => { await act(async () => { extend({ MyColor }) // @ts-expect-error we're testing the extend feature, i'm not adding it to the namespace render(<myColor args={[0x0000ff]} />, canvas) }) }).not.toThrow() }) })