diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index 701c3518d..0207c508a 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -58,7 +58,7 @@ jobs: run: BUILD_BRANCH=$(echo "${GITHUB_REF#refs/heads/}") npm run build - name: Store assets - if: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/development' || github.ref == 'refs/heads/master') }} + if: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/rum-agent-integration/suite' || github.ref == 'refs/heads/master') }} uses: actions/upload-artifact@v3 with: name: assets @@ -69,7 +69,7 @@ jobs: name: Upload assets runs-on: ubuntu-20.04 needs: build - if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/development' }} + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/rum-agent-integration/suite' }} strategy: matrix: environment: diff --git a/CHANGES.txt b/CHANGES.txt index 8cdc48f85..63df16751 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -2,7 +2,7 @@ - Updated @splitsoftware/splitio-commons package to version 1.9.1. This update removes the handler for 'unload' DOM events, that can prevent browsers from being able to put pages in the back/forward cache for faster back and forward loads (Related to issue https://github.com/splitio/javascript-client/issues/759). 10.23.0 (July 18, 2023) - - Updated @splitsoftware/splitio-commons package to version 1.8.4 that includes minor improvements: + - Updated @splitsoftware/splitio-commons package to version 1.9.0 that includes minor improvements: - Updated streaming architecture implementation to apply feature flag updates from the notification received which is now enhanced, improving efficiency and reliability of the whole update system. 10.22.6 (July 6, 2023) diff --git a/karma/e2e.suite.karma.conf.js b/karma/e2e.suite.karma.conf.js new file mode 100644 index 000000000..f030fe703 --- /dev/null +++ b/karma/e2e.suite.karma.conf.js @@ -0,0 +1,20 @@ +const assign = require('lodash/assign'); + +module.exports = function(config) { + 'use strict'; + + config.set(assign({}, require('./config'), { + // list of files / patterns to load in the browser + files: [ + '__tests__/suite/browser.spec.js' + ], + // prepare code for the browser using webpack + preprocessors: { + '__tests__/suite/browser.spec.js': ['webpack'] + }, + + // level of logging + // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG + logLevel: config.LOG_WARN + })); +}; diff --git a/package-lock.json b/package-lock.json index 976d0a61a..15647b5cd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,16 @@ { "name": "@splitsoftware/splitio", - "version": "10.23.1", + "version": "10.23.1-rc.3", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@splitsoftware/splitio", - "version": "10.23.1", + "version": "10.23.1-rc.3", "license": "Apache-2.0", "dependencies": { - "@splitsoftware/splitio-commons": "1.9.1", + "@splitsoftware/browser-rum-agent": "0.3.2-rc.0", + "@splitsoftware/splitio-commons": "1.9.2-rc.2", "@types/google.analytics": "0.0.40", "@types/ioredis": "^4.28.0", "bloom-filters": "^3.0.0", @@ -801,10 +802,18 @@ "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==", "dev": true }, + "node_modules/@splitsoftware/browser-rum-agent": { + "version": "0.3.2-rc.0", + "resolved": "https://registry.npmjs.org/@splitsoftware/browser-rum-agent/-/browser-rum-agent-0.3.2-rc.0.tgz", + "integrity": "sha512-AR++6xvzNHHA0575GpfvOo7c2Vkx9xAI7oCWiU24Y3kiSZrz7WPfU0dK5J9UUgcgmiTnyxcOkwJlIld2f0AHVQ==", + "dependencies": { + "web-vitals": "^3.1.0" + } + }, "node_modules/@splitsoftware/splitio-commons": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@splitsoftware/splitio-commons/-/splitio-commons-1.9.1.tgz", - "integrity": "sha512-+1lFUBj+Jgfd8l7nT49+rZodwgZXJ6c20+4PPb0O+iTmUZXHtYvfS2AK8A9j6QREubeccc6UMlfjH3SQVgwEbg==", + "version": "1.9.2-rc.2", + "resolved": "https://registry.npmjs.org/@splitsoftware/splitio-commons/-/splitio-commons-1.9.2-rc.2.tgz", + "integrity": "sha512-feg1LCdDTQ+kYBrkU7PwzRRJ6Vs/u5lqrZj6lLiHTTT3xvsKRQi07XAYuFnEJQrNXqJZmzP7jPJARWR/n6svdA==", "dependencies": { "tslib": "^2.3.1" }, @@ -7341,6 +7350,11 @@ "node": ">=10.13.0" } }, + "node_modules/web-vitals": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-3.4.0.tgz", + "integrity": "sha512-n9fZ5/bG1oeDkyxLWyep0eahrNcPDF6bFqoyispt7xkW0xhDzpUBTgyDKqWDi1twT0MgH4HvvqzpUyh0ZxZV4A==" + }, "node_modules/webidl-conversions": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", @@ -8311,10 +8325,18 @@ "integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg==", "dev": true }, + "@splitsoftware/browser-rum-agent": { + "version": "0.3.2-rc.0", + "resolved": "https://registry.npmjs.org/@splitsoftware/browser-rum-agent/-/browser-rum-agent-0.3.2-rc.0.tgz", + "integrity": "sha512-AR++6xvzNHHA0575GpfvOo7c2Vkx9xAI7oCWiU24Y3kiSZrz7WPfU0dK5J9UUgcgmiTnyxcOkwJlIld2f0AHVQ==", + "requires": { + "web-vitals": "^3.1.0" + } + }, "@splitsoftware/splitio-commons": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@splitsoftware/splitio-commons/-/splitio-commons-1.9.1.tgz", - "integrity": "sha512-+1lFUBj+Jgfd8l7nT49+rZodwgZXJ6c20+4PPb0O+iTmUZXHtYvfS2AK8A9j6QREubeccc6UMlfjH3SQVgwEbg==", + "version": "1.9.2-rc.2", + "resolved": "https://registry.npmjs.org/@splitsoftware/splitio-commons/-/splitio-commons-1.9.2-rc.2.tgz", + "integrity": "sha512-feg1LCdDTQ+kYBrkU7PwzRRJ6Vs/u5lqrZj6lLiHTTT3xvsKRQi07XAYuFnEJQrNXqJZmzP7jPJARWR/n6svdA==", "requires": { "tslib": "^2.3.1" } @@ -13374,6 +13396,11 @@ "graceful-fs": "^4.1.2" } }, + "web-vitals": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-3.4.0.tgz", + "integrity": "sha512-n9fZ5/bG1oeDkyxLWyep0eahrNcPDF6bFqoyispt7xkW0xhDzpUBTgyDKqWDi1twT0MgH4HvvqzpUyh0ZxZV4A==" + }, "webidl-conversions": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", diff --git a/package.json b/package.json index 10c413c7f..9c8527754 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@splitsoftware/splitio", - "version": "10.23.1", + "version": "10.23.1-rc.3", "description": "Split SDK", "files": [ "README.md", @@ -12,6 +12,7 @@ "es", "src", "scripts/ga-to-split-autorequire.js", + "suite", "client", "server" ], @@ -40,7 +41,8 @@ "node": ">=6" }, "dependencies": { - "@splitsoftware/splitio-commons": "1.9.1", + "@splitsoftware/browser-rum-agent": "0.3.2-rc.0", + "@splitsoftware/splitio-commons": "1.9.2-rc.2", "@types/google.analytics": "0.0.40", "@types/ioredis": "^4.28.0", "bloom-filters": "^3.0.0", @@ -100,13 +102,14 @@ "check:version": "cross-env NODE_ENV=test tape -r ./ts-node.register src/settings/__tests__/defaults.spec.js", "test-browser": "npm run test-browser-unit && npm run test-browser-e2e", "test-browser-unit": "cross-env NODE_ENV=test karma start karma/unit.karma.conf.js", - "test-browser-e2e": "npm run test-browser-e2e-online && npm run test-browser-e2e-offline && npm run test-browser-e2e-destroy && npm run test-browser-e2e-errorCatching && npm run test-browser-e2e-push && npm run test-browser-e2e-gaIntegration", + "test-browser-e2e": "npm run test-browser-e2e-online && npm run test-browser-e2e-offline && npm run test-browser-e2e-destroy && npm run test-browser-e2e-errorCatching && npm run test-browser-e2e-push && npm run test-browser-e2e-gaIntegration && npm run test-browser-e2e-suite", "test-browser-e2e-online": "cross-env NODE_ENV=test karma start karma/e2e.online.karma.conf.js", "test-browser-e2e-offline": "cross-env NODE_ENV=test karma start karma/e2e.offline.karma.conf.js", "test-browser-e2e-destroy": "cross-env NODE_ENV=test karma start karma/e2e.destroy.karma.conf.js", "test-browser-e2e-errorCatching": "cross-env NODE_ENV=test karma start karma/e2e.errorCatching.karma.conf.js", "test-browser-e2e-push": "cross-env NODE_ENV=test karma start karma/e2e.push.karma.conf.js", "test-browser-e2e-gaIntegration": "cross-env NODE_ENV=test karma start karma/e2e.gaIntegration.karma.conf.js", + "test-browser-e2e-suite": "cross-env NODE_ENV=test karma start karma/e2e.suite.karma.conf.js", "test-node": "npm run test-node-unit && npm run test-node-e2e", "test-node-unit": "cross-env NODE_ENV=test tape -r ./ts-node.register \"src/*/**/__tests__/**/!(browser).spec.js\" | tap-min", "test-node-e2e": "npm run test-node-e2e-online && npm run test-node-e2e-offline && npm run test-node-e2e-destroy && npm run test-node-e2e-errorCatching && npm run test-node-e2e-push && npm run test-node-e2e-redis", diff --git a/src/__tests__/destroy/browser.spec.js b/src/__tests__/destroy/browser.spec.js index 8f486191a..26fd25c93 100644 --- a/src/__tests__/destroy/browser.spec.js +++ b/src/__tests__/destroy/browser.spec.js @@ -19,7 +19,7 @@ const settings = settingsFactory({ }); fetchMock.getOnce(url(settings, '/splitChanges?since=-1'), { status: 200, body: splitChangesMock1 }); -fetchMock.getOnce(url(settings, '/splitChanges?since=-1500492097547'), { status: 200, body: splitChangesMock2 }); +fetchMock.getOnce(url(settings, '/splitChanges?since=1500492097547'), { status: 200, body: splitChangesMock2 }); fetchMock.getOnce(url(settings, '/mySegments/ut1'), { status: 200, body: mySegmentsMock }); fetchMock.getOnce(url(settings, '/mySegments/ut2'), { status: 200, body: mySegmentsMock }); fetchMock.getOnce(url(settings, '/mySegments/ut3'), { status: 200, body: mySegmentsMock }); diff --git a/src/__tests__/destroy/node.spec.js b/src/__tests__/destroy/node.spec.js index c0a0b8d78..32b171f7b 100644 --- a/src/__tests__/destroy/node.spec.js +++ b/src/__tests__/destroy/node.spec.js @@ -18,7 +18,7 @@ import splitChangesMock2 from '../mocks/splitChanges.since.1500492097547.json'; import impressionsMock from '../mocks/impressions.json'; fetchMock.get(url(settings, '/splitChanges?since=-1'), { status: 200, body: splitChangesMock1 }); -fetchMock.get(url(settings, '/splitChanges?since=-1500492097547'), { status: 200, body: splitChangesMock2 }); +fetchMock.get(url(settings, '/splitChanges?since=1500492097547'), { status: 200, body: splitChangesMock2 }); fetchMock.postOnce(url(settings, '/v1/metrics/config'), 200); tape('SDK destroy for NodeJS', async function (assert) { diff --git a/src/__tests__/suite/browser.spec.js b/src/__tests__/suite/browser.spec.js new file mode 100644 index 000000000..5273ab52a --- /dev/null +++ b/src/__tests__/suite/browser.spec.js @@ -0,0 +1,165 @@ +import sinon from 'sinon'; +import tape from 'tape-catch'; +import fetchMock from '../testUtils/fetchMock'; +import { url } from '../testUtils'; +import { settingsFactory } from '../../settings'; + +import splitChangesMock1 from '../mocks/splitChanges.since.-1.till.1500492097547.json'; +import splitChangesMock2 from '../mocks/splitChanges.since.1500492097547.json'; +import mySegmentsMock from '../mocks/mySegmentsEmpty.json'; +import { triggerPagehideEvent } from '../testUtils/browser'; +import { version } from '../../../node_modules/@splitsoftware/browser-rum-agent/package.json'; + +// Test target +import { SplitSuite } from '../../factory/browserSuite'; + +tape('Split Suite: Browser SDK & RUM Agent', async function (assert) { + const config = { + core: { + authorizationKey: 'fake-key', + key: 'ut1' + }, + streamingEnabled: false, + rumAgent: { + prefix: 'prefix' + } + }; + + // Mock fetch requests + const settings = settingsFactory(config); + fetchMock.getOnce(url(settings, '/splitChanges?since=-1'), { status: 200, body: splitChangesMock1 }); + fetchMock.getOnce(url(settings, '/splitChanges?since=1500492097547'), { status: 200, body: splitChangesMock2 }); + fetchMock.getOnce(url(settings, '/mySegments/ut1'), { status: 200, body: mySegmentsMock }); + fetchMock.getOnce(url(settings, '/mySegments/ut2'), { status: 200, body: mySegmentsMock }); + fetchMock.getOnce(url(settings, '/mySegments/ut3'), { status: 200, body: mySegmentsMock }); + fetchMock.postOnce(url(settings, '/v1/metrics/config'), 200); // 0.1% sample rate + + const suite = SplitSuite(config); + + // Assert RUM-Agent is properly configured + assert.deepEqual(window.SplitRumAgent.__getConfig(), { + i: [], a: 'fake-key', p: {}, + prefix: settings.rumAgent.prefix, + url: settings.urls.events, + log: settings.log, + userConsent: settings.userConsent, + pushRate: 30, queueSize: 5000, // RUM Agent has its own push rate and queue size + }, 'RUM Agent is properly configured.'); + assert.deepEqual(window.SplitRumAgent.getIdentities(), [], 'No identities are added to the RUM Agent until clients are retrieved.'); + + const client = suite.client(); + assert.deepEqual(window.SplitRumAgent.getIdentities(), [{ key: config.core.key, trafficType: 'user' }], 'Identity for the main client.'); + + const client2 = suite.client('ut2'); + const client3 = suite.client('ut3', 'tt2'); + assert.deepEqual(window.SplitRumAgent.getIdentities(), [{ + key: config.core.key, trafficType: 'user' + }, { + key: 'ut2', trafficType: 'user' + }, { + key: 'ut3', trafficType: 'tt2' + }], 'Identity for the main and shared clients.'); + + window.SplitRumAgent.track('custom-event-for-all-clients'); + + const manager = suite.manager(); + + client.track('tt2', 'eventType', 1); + client2.track('tt', 'eventType', 2); + client3.track('otherEventType', 3); + + // Assert we are sending the impressions while doing the destroy + fetchMock.postOnce(url(settings, '/testImpressions/bulk'), 200); + + // Assert we are sending the impressions count while doing the destroy + fetchMock.postOnce(url(settings, '/testImpressions/count'), 200); + + // Assert we are sending events tracked by SDK clients, while doing the destroy + fetchMock.postOnce(url(settings, '/events/bulk'), (url, opts) => { + const events = JSON.parse(opts.body); + + /* 3 events were pushed */ + assert.equal(events.length, 3, 'Should flush all events on destroy.'); + + const firstEvent = events[0]; + const secondEvent = events[1]; + const thirdEvent = events[2]; + + assert.equal(firstEvent.trafficTypeName, 'tt2', 'The flushed events should match the events on the queue.'); + assert.equal(firstEvent.eventTypeId, 'eventType', 'The flushed events should match the events on the queue.'); + assert.equal(firstEvent.value, 1, 'The flushed events should match the events on the queue.'); + assert.equal(secondEvent.trafficTypeName, 'tt', 'The flushed events should match the events on the queue.'); + assert.equal(secondEvent.eventTypeId, 'eventType', 'The flushed events should match the events on the queue.'); + assert.equal(secondEvent.value, 2, 'The flushed events should match the events on the queue.'); + assert.equal(thirdEvent.trafficTypeName, 'tt2', 'The flushed events should match the events on the queue.'); + assert.equal(thirdEvent.eventTypeId, 'otherEventType', 'The flushed events should match the events on the queue.'); + assert.equal(thirdEvent.value, 3, 'The flushed events should match the events on the queue.'); + + return 200; + }); + + await client.ready(); + + assert.equal(client.getTreatment('Single_Test'), 'on'); + assert.equal(client2.getTreatment('Single_Test'), 'on'); + assert.equal(client3.getTreatment('Single_Test'), 'on'); + assert.ok(manager.splits().length > 0, 'control assertion'); + assert.ok(manager.names().length > 0, 'control assertion'); + assert.ok(manager.split('Single_Test'), 'control assertion'); + + // Assert that the RUM Agent flush events on pagehide event + const sendBeaconSpy = sinon.spy(window.navigator, 'sendBeacon'); + triggerPagehideEvent(); + + const eventsCallArgs = sendBeaconSpy.firstCall.args; + assert.equal(eventsCallArgs[0], url(settings, '/events/beacon'), 'assert correct url'); + const parsedPayload = JSON.parse(eventsCallArgs[1]); + assert.equal(parsedPayload.token, 'fake-key', 'assert correct payload token'); + assert.equal(parsedPayload.sdk, 'jsrum-' + version, 'assert correct sdk version'); + assert.deepEqual(parsedPayload.entries.map(event => ({ eventTypeId: event.eventTypeId, key: event.key, trafficTypeName: event.trafficTypeName })), [ + { trafficTypeName: 'user', key: 'ut1', eventTypeId: 'prefix.custom-event-for-all-clients' }, + { trafficTypeName: 'user', key: 'ut2', eventTypeId: 'prefix.custom-event-for-all-clients' }, + { trafficTypeName: 'tt2', key: 'ut3', eventTypeId: 'prefix.custom-event-for-all-clients' }, + { trafficTypeName: 'user', key: 'ut1', eventTypeId: 'prefix.time.to.dom.interactive' }, + { trafficTypeName: 'user', key: 'ut2', eventTypeId: 'prefix.time.to.dom.interactive' }, + { trafficTypeName: 'tt2', key: 'ut3', eventTypeId: 'prefix.time.to.dom.interactive' }, + { trafficTypeName: 'user', key: 'ut1', eventTypeId: 'prefix.page.load.time' }, + { trafficTypeName: 'user', key: 'ut2', eventTypeId: 'prefix.page.load.time' }, + { trafficTypeName: 'tt2', key: 'ut3', eventTypeId: 'prefix.page.load.time' }, + ], 'assert correct entries'); + + // Events are not sent again + triggerPagehideEvent(); + assert.equal(sendBeaconSpy.callCount, 3, 'sendBeacon should have been called 3 times'); + assert.ok(sendBeaconSpy.firstCall.calledWith(url(settings, '/events/beacon')), 'RUM Agent events'); + assert.ok(sendBeaconSpy.secondCall.calledWith(url(settings, '/testImpressions/beacon')), 'SDK impressions'); + assert.ok(sendBeaconSpy.thirdCall.calledWith(url(settings, '/events/beacon')), 'SDK events'); + + // Updating user consent should update the RUM Agent user consent + assert.ok(suite.UserConsent.setStatus(false)); + assert.equal(suite.UserConsent.getStatus(), 'DECLINED'); + assert.equal(window.SplitRumAgent.getUserConsent(), 'DECLINED'); + + assert.ok(suite.UserConsent.setStatus(true)); + assert.equal(suite.UserConsent.getStatus(), 'GRANTED'); + assert.equal(window.SplitRumAgent.getUserConsent(), 'GRANTED'); + + assert.notOk(suite.UserConsent.setStatus('invalid')); + assert.equal(suite.UserConsent.getStatus(), 'GRANTED'); + assert.equal(window.SplitRumAgent.getUserConsent(), 'GRANTED'); + + // Calls `client.destroy()` for all clients + const destroyPromise = suite.destroy(); + assert.equal(client.getTreatment('Single_Test'), 'control', 'After destroy, getTreatment returns control for every destroyed client.'); + assert.deepEqual(client2.getTreatments(['Single_Test']), { 'Single_Test': 'control' }, 'After destroy, getTreatments returns map of controls for every destroyed client.'); + assert.notOk(client3.track('tt', 'eventType', 2), 'After destroy, track calls return false.'); + assert.equal(manager.splits().length, 0, 'After the main client is destroyed, manager.splits will return empty array'); + assert.equal(manager.names().length, 0, 'After the main client is destroyed, manager.names will return empty array'); + assert.equal(manager.split('Single_Test'), null, 'After the main client is destroyed, manager.split will return null'); + + await destroyPromise; + fetchMock.restore(); + sendBeaconSpy.restore(); + + assert.end(); +}); diff --git a/src/factory/browserSuite.js b/src/factory/browserSuite.js new file mode 100644 index 000000000..3e2e6e4ad --- /dev/null +++ b/src/factory/browserSuite.js @@ -0,0 +1,79 @@ +import { objectAssign } from '@splitsoftware/splitio-commons/src/utils/lang/objectAssign'; +import { _Set, setToArray } from '@splitsoftware/splitio-commons/src/utils/lang/sets'; +import { STANDALONE_MODE } from '@splitsoftware/splitio-commons/src/utils/constants'; +// @TODO import RumAgent automatically or users should import it? +import { SplitRumAgent } from '@splitsoftware/browser-rum-agent'; +import { SplitFactory } from './browser'; + +const DEFAULT_TRAFFIC_TYPE = 'user'; + +/** + * SplitFactory for client-side with RUM Agent. + * + * @param {import('../../types/splitio').IBrowserSuiteSettings} config configuration object used to instantiate the Suite + * @param {Function=} __updateModules optional function that lets redefine internal SDK modules. Use with + * caution since, unlike `config`, this param is not validated neither considered part of the public API. + * @throws Will throw an error if the provided config is invalid. + */ +export function SplitSuite(config, __updateModules) { + const sdk = SplitFactory(config, __updateModules); + + /** @type {import('../../types/splitio').IBrowserSuiteSettings} */ + const settings = sdk.settings; + + // Do not setup RUM Agent if not in standalone mode + if (settings.mode !== STANDALONE_MODE) return sdk; + + // Setup RUM Agent + const agentConfig = SplitRumAgent.__getConfig(); + if (agentConfig.a) { + settings.log.warn('RUM Agent already setup. The new Suite instance will reset the RUM Agent configuration.'); + } + agentConfig.log = settings.log; + SplitRumAgent.removeIdentities(); // reset identities for new Suite + SplitRumAgent.setup(settings.core.authorizationKey, objectAssign({ + url: settings.urls.events, + userConsent: settings.userConsent + }, settings.rumAgent)); + + const clients = new _Set(); + + // Override UserConsent.setStatus to update RUM Agent consent + const originalSetStatus = sdk.UserConsent.setStatus; + sdk.UserConsent.setStatus = function (newStatus) { + SplitRumAgent.setUserConsent(newStatus); + return originalSetStatus.apply(this, arguments); + }; + + // Create Suite instance extending SDK + return objectAssign({}, sdk, { + client() { + const client = sdk.client.apply(sdk, arguments); + + if (!clients.has(client)) { + clients.add(client); + + SplitRumAgent.addIdentity({ + key: client.key, + trafficType: client.trafficType || DEFAULT_TRAFFIC_TYPE + }); + + // override client.destroy to remove identity from RUM Agent + const originalDestroy = client.destroy; + client.destroy = function () { + SplitRumAgent.removeIdentity({ + key: client.key, + trafficType: client.trafficType || DEFAULT_TRAFFIC_TYPE + }); + return originalDestroy.apply(client, arguments); + }; + } + + return client; + }, + + destroy() { + return Promise.all(setToArray(clients).map(client => client.destroy())); + } + }); +} diff --git a/src/settings/defaults/version.js b/src/settings/defaults/version.js index fc16e17c3..3c30ad65f 100644 --- a/src/settings/defaults/version.js +++ b/src/settings/defaults/version.js @@ -1 +1 @@ -export const packageVersion = '10.23.1'; +export const packageVersion = '10.23.1-rc.3'; diff --git a/suite/package.json b/suite/package.json new file mode 100644 index 000000000..a36b6d46d --- /dev/null +++ b/suite/package.json @@ -0,0 +1,5 @@ +{ + "main": "../lib/factory/browserSuite.js", + "module": "../es/factory/browserSuite.js", + "types": "../types/suite/index.d.ts" +} diff --git a/ts-tests/index.ts b/ts-tests/index.ts index 51d2322f0..de4fdb651 100644 --- a/ts-tests/index.ts +++ b/ts-tests/index.ts @@ -12,6 +12,8 @@ */ import { SplitFactory } from '@splitsoftware/splitio'; +import { SplitSuite } from '@splitsoftware/splitio/suite'; +import { EventData } from '@splitsoftware/browser-rum-agent'; let stringPromise: Promise; let splitNamesPromise: Promise; @@ -621,3 +623,21 @@ let fullAsyncSettings: SplitIO.INodeAsyncSettings = { fullBrowserSettings.debug = 'ERROR'; fullNodeSettings.debug = 'WARN'; fullAsyncSettings.debug = 'INFO'; + +// Suite +const suiteConfig: SplitIO.IBrowserSuiteSettings = { + ...browserSettings, + rumAgent: { + prefix: 'prefix', + pushRate: 1, + queueSize: 1 + } +} +const suite = SplitSuite(suiteConfig); + +SDK = suite; // The Suite interface extends the SDK interface + +client = suite.client(); +client = suite.client('key'); +client = suite.client('key', 'trafficType'); +let promise: Promise = suite.destroy(); diff --git a/ts-tests/package.json b/ts-tests/package.json index 3ea5704a1..4b5cd69e3 100644 --- a/ts-tests/package.json +++ b/ts-tests/package.json @@ -6,7 +6,7 @@ "license": "Apache-2.0", "repository": "splitio/javascript-client", "dependencies": { - "@types/node": "^14.18.52", - "typescript": "^3.7.4" + "@types/node": "^14.18.56", + "typescript": "^4.9.5" } } diff --git a/ts-tests/tsconfig.json b/ts-tests/tsconfig.json index 4adc23925..1f7f077ef 100644 --- a/ts-tests/tsconfig.json +++ b/ts-tests/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "noImplicitAny": true, "target": "es5", - "module": "commonjs" + "module": "commonjs", + "skipLibCheck": true, }, "files": [ "index" diff --git a/types/splitio.d.ts b/types/splitio.d.ts index 38f9c2edc..b4623e9d1 100644 --- a/types/splitio.d.ts +++ b/types/splitio.d.ts @@ -4,6 +4,7 @@ /// import { RedisOptions } from "ioredis"; +import { SplitRumAgentConfig, EventCollector } from '@splitsoftware/browser-rum-agent'; export as namespace SplitIO; export = SplitIO; @@ -1119,6 +1120,19 @@ declare namespace SplitIO { */ userConsent?: ConsentStatus } + /** + * Settings interface for Suite instances created on the browser. + * @interface IBrowserSuiteSettings + * @extends IBrowserSettings + * @see {@link https://help.split.io/hc/en-us/articles/360020448791-JavaScript-SDK#configuration} + */ + interface IBrowserSuiteSettings extends IBrowserSettings { + /** + * Optional configuration object for the RUM agent. + * @see {@link https://help.split.io/hc/en-us/articles/360030898431-Browser-RUM-agent#configuration} + */ + rumAgent?: SplitRumAgentConfig + } /** * Settings interface for SDK instances created on NodeJS. * If your storage is asynchronous (Redis for example) use SplitIO.INodeAsyncSettings instead. @@ -1288,8 +1302,8 @@ declare namespace SplitIO { } /** * This represents the interface for the SDK instance with synchronous storage. - * @interface ISDK - * @extends IBasicSDK + * @interface IBrowserSDK + * @extends ISDK */ interface IBrowserSDK extends ISDK { /** @@ -1312,6 +1326,41 @@ declare namespace SplitIO { */ UserConsent: IUserConsentAPI } + /** + * This represents the interface for the Suite instance, that is an extension of the SDK interface. + * @interface IBrowserSuiteSDK + * @extends IBrowserSDK + */ + interface IBrowserSuiteSDK extends IBrowserSDK { + /** + * Returns the default client instance of the SDK, and adds its identity (i.e., user key and traffic type pair) to the RUM agent to track events for it. + * + * NOTE: if no traffic type was provided to the config, 'user' will be used as default for the RUM Agent. + * + * @function client + * @returns {IBrowserClient} The client instance. + */ + client(): IBrowserClient, + /** + * Returns a shared client of the SDK, and adds its identity (i.e., user key and traffic type pair) to the RUM agent to track events for it. + * + * NOTE: if no traffic type is provided as second argument, 'user' will be used as default for the RUM Agent. + * + * @function client + * @param {SplitKey} key The key for the new client instance. + * @param {string=} trafficType The traffic type of the provided key. + * @returns {IBrowserClient} The client instance. + */ + client(key: SplitKey, trafficType?: string): IBrowserClient + /** + * Destroys all client instances and remove identities from the RUM agent to stop tracking events for them. + * This method will flush any pending impressions and events, and stop the synchronization of feature flag definitions with the backend. + * + * @function destroy + * @returns {Promise} A promise that resolves once the client is destroyed. + */ + destroy(): Promise + } /** * This represents the interface for the SDK instance with asynchronous storage. * @interface IAsyncSDK diff --git a/types/suite/index.d.ts b/types/suite/index.d.ts new file mode 100644 index 000000000..d3f3976d3 --- /dev/null +++ b/types/suite/index.d.ts @@ -0,0 +1,12 @@ +// Declaration file for JavaScript Split Software SDK +// Project: http://www.split.io/ + +/// +export = JsSdk; + +declare module JsSdk { + /** + * @TODO + */ + export function SplitSuite(settings: SplitIO.IBrowserSuiteSettings): SplitIO.IBrowserSuiteSDK; +}