├── .editorconfig ├── .github ├── stale.yml └── workflows │ ├── add-to-project.yml │ ├── ci.yml │ └── release.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── examples └── README.md ├── jest.config.js ├── package.json ├── rollup.config.mjs ├── setupJest.js ├── src ├── events-handler.ts ├── index.test.ts ├── index.ts ├── metrics.test.ts ├── metrics.ts ├── storage-provider-inmemory.test.ts ├── storage-provider-inmemory.ts ├── storage-provider-local.test.ts ├── storage-provider-local.ts ├── storage-provider.ts ├── test │ ├── index.html │ ├── index.ts │ └── testdata.json ├── util.test.ts ├── util.ts ├── uuidv4.ts └── version.ts ├── tsconfig.json └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | indent_style = space 8 | indent_size = 4 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | 15 | [*.json] 16 | indent_size = 2 17 | 18 | [*.yaml] 19 | indent_size = 2 20 | 21 | [*.yml] 22 | indent_size = 2 23 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | _extends: .github 2 | -------------------------------------------------------------------------------- /.github/workflows/add-to-project.yml: -------------------------------------------------------------------------------- 1 | name: Add new item to project board 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | pull_request_target: 8 | types: 9 | - opened 10 | 11 | jobs: 12 | add-to-project: 13 | uses: unleash/.github/.github/workflows/add-item-to-project.yml@main 14 | secrets: inherit 15 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Node.js CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [16.x, 18.x, 20.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | id: setup-git-checkout 20 | with: 21 | fetch-depth: 25 22 | 23 | - uses: actions/setup-node@v3 24 | id: setup-node 25 | with: 26 | node-version: ${{ matrix.node-version }} 27 | cache: 'yarn' 28 | 29 | - name: 📌 Install 30 | run: yarn install --frozen-lockfile 31 | 32 | - name: 🔨 Build 33 | run: yarn build 34 | 35 | - name: ✨ Lint 36 | run: yarn lint 37 | 38 | - name: 🧪 Test 39 | run: npm test 40 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: 🚀 Release 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: New version semver (e.g. 3.7.0) 8 | required: true 9 | type: string 10 | tag: 11 | description: NPM tag 12 | required: false 13 | type: string 14 | default: 'latest' 15 | 16 | jobs: 17 | from-template: 18 | uses: Unleash/.github/.github/workflows/npm-release.yml@v2.0.0 19 | with: 20 | version: ${{ github.event.inputs.version }} 21 | tag: ${{ github.event.inputs.tag }} 22 | secrets: 23 | NPM_ACCESS_TOKEN: ${{ secrets.NPM_TOKEN }} 24 | UNLEASH_BOT_APP_ID: ${{ secrets.UNLEASH_BOT_APP_ID }} 25 | UNLEASH_BOT_PRIVATE_KEY: ${{ secrets.UNLEASH_BOT_PRIVATE_KEY }} 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | node_modules/ 3 | .vscode/ 4 | coverage/ 5 | .idea 6 | .DS_Store 7 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "es5" 4 | } 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Bricks Software AS 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unleash Proxy Client for the browser (JS) 2 | 3 | The JavaScript client is a tiny Unleash client written in JavaScript without any external dependencies (except from browser APIs). This client stores toggles relevant for the current user in `localStorage` and synchronizes with Unleash (the [Unleash front-end API](https://docs.getunleash.io/reference/front-end-api) _or_ [Unleash edge](https://docs.getunleash.io/reference/unleash-edge)) in the background. Because toggles are stored in the user's browser, the client can use them to bootstrap itself the next time the user visits the same web page. 4 | 5 | This client expect `fetch` to be available. 6 | 7 | ## Frameworks supported 8 | 9 | This package is not tied to any framework, but can be used together most popular frameworks, examples: 10 | 11 | - [Unleash React SDK](https://docs.getunleash.io/reference/sdks/react) 12 | - [React](https://reactjs.org/) 13 | - [React Native](https://reactnative.dev/) 14 | - [Angular JS](https://angularjs.org/) 15 | - [Vue.js](https://vuejs.org/) 16 | - ...and probably your favorite! 17 | 18 | ## How to use the client 19 | 20 | ### Step 1: Installation 21 | 22 | ```js 23 | npm install unleash-proxy-client 24 | ``` 25 | 26 | ### Step 2: Initialize the SDK 27 | 28 | --- 29 | 30 | 💡 **TIP**: As a client-side SDK, this SDK requires you to connect to either Unleash Edge or to the Unleash front-end API. Refer to the [connection options section](#connection-options) for more information. 31 | 32 | --- 33 | 34 | Configure the client according to your needs. The following example provides only the required options. Refer to [the section on available options](#available-options) for the full list. 35 | 36 | ```js 37 | import { UnleashClient } from 'unleash-proxy-client'; 38 | 39 | const unleash = new UnleashClient({ 40 | url: 'https:///api/frontend', 41 | clientKey: '', 42 | appName: 'my-webapp', 43 | }); 44 | 45 | // Start the background polling 46 | unleash.start(); 47 | ``` 48 | 49 | #### Connection options 50 | 51 | To connect this SDK to your Unleash instance's [front-end API](https://docs.getunleash.io/reference/front-end-api), use the URL to your Unleash instance's front-end API (`/api/frontend`) as the `url` parameter. For the `clientKey` parameter, use a `FRONTEND` token generated from your Unleash instance. Refer to the [_how to create API tokens_](https://docs.getunleash.io/how-to/how-to-create-api-tokens) guide for the necessary steps. 52 | 53 | This SDK can also be used with [Unleash Edge](https://docs.getunleash.io/reference/unleash-edge). 54 | 55 | ### Step 3: Let the client synchronize 56 | 57 | You should wait for the client's `ready` or `initialized` events before you start working with it. Before it's ready, the client might not report the correct state for your features. 58 | 59 | ```js 60 | unleash.on('ready', () => { 61 | if (unleash.isEnabled('js.demo')) { 62 | console.log('js.demo is enabled'); 63 | } else { 64 | console.log('js.demo is disabled'); 65 | } 66 | }); 67 | ``` 68 | 69 | The difference between the events is described in the [section on available events](#available-events). 70 | 71 | ### Step 4: Check feature toggle states 72 | 73 | Once the client is ready, you can start checking features in your application. Use the `isEnabled` method to check the state of any feature you want: 74 | 75 | ```js 76 | unleash.isEnabled('js.demo'); 77 | ``` 78 | 79 | You can use the `getVariant` method to get the variant of an **enabled feature that has variants**. If the feature is disabled or if it has no variants, then you will get back the [**disabled variant**](https://docs.getunleash.io/reference/feature-toggle-variants#the-disabled-variant) 80 | 81 | ```js 82 | const variant = unleash.getVariant('proxy.demo'); 83 | if (variant.name === 'blue') { 84 | // something with variant blue... 85 | } 86 | ``` 87 | 88 | #### Updating the Unleash context 89 | 90 | The [Unleash context](https://docs.getunleash.io/reference/unleash-context) is used to evaluate features against attributes of a the current user. To update and configure the Unleash context in this SDK, use the `updateContext`, `setContextField` and `removeContextField` methods. 91 | 92 | The context you set in your app will be passed along to the Unleash proxy or the front-end API as query parameters for feature evaluation. 93 | 94 | The `updateContext` method will replace the entire 95 | (mutable part) of the Unleash context with the data that you pass in. 96 | 97 | The `setContextField` method only acts on the property that you choose. It does not affect any other properties of the Unleash context. 98 | 99 | ```js 100 | unleash.updateContext({ userId: '1233' }); 101 | 102 | unleash.setContextField('userId', '4141'); 103 | ``` 104 | 105 | The `removeContextField` method only acts on the property that you choose. It does not affect any other properties of the Unleash context. 106 | 107 | ```js 108 | unleash.updateContext({ userId: '1233', sessionId: 'sessionNotAffected' }); 109 | 110 | unleash.removeContextField('userId'); 111 | ``` 112 | 113 | ### Available options 114 | 115 | The Unleash SDK takes the following options: 116 | 117 | | option | required | default | description | 118 | |-------------------|----------|---------|--------------------------------------------------------------------------------------------------------------------------------------------------| 119 | | url | yes | n/a | The Unleash URL to connect to. E.g.: `https://examples.com/api/front-end` | 120 | | clientKey | yes | n/a | The Unleash API Secret to be used | 121 | | appName | yes | n/a | The name of the application using this SDK. Will be used as part of the metrics sent to Unleash. Will also be part of the Unleash Context. | 122 | | context | no | `{}` | The initial Unleash context. This will be used as the initial context for all feature toggle evaluations. The `appName` and `environment` options will automatically be populated with the values you pass for those options. | 123 | | refreshInterval | no | `30` | How often, in seconds, the SDK should check for updated toggle configuration. If set to 0 will disable checking for updates | 124 | | disableRefresh | no | `false` | If set to true, the client will not check for updated toggle configuration | 125 | | metricsInterval | no | `60` | How often, in seconds, the SDK should send usage metrics back to Unleash. It will be started after the initial metrics report, which is sent after the configured `metricsIntervalInitial` | 126 | | metricsIntervalInitial | no | `2` | How long the SDK should wait for the first metrics report back to the Unleash API. If you want to disable the initial metrics call you can set it to 0. | 127 | | disableMetrics | no | `false` | Set this option to `true` if you want to disable usage metrics | 128 | | storageProvider | no | `LocalStorageProvider` in browser, `InMemoryStorageProvider` otherwise | Allows you to inject a custom storeProvider | 129 | | fetch | no | `window.fetch` or global `fetch` | Allows you to override the fetch implementation to use. Useful in Node.js environments where you can inject `node-fetch` | 130 | | createAbortController | no | `() => new AbortController()` | Allows you to override the default `AbortController` creation. Used to cancel requests with outdated context. Set it to `() => null` if you don't want to handle it. | 131 | | bootstrap | no | `[]` | Allows you to bootstrap the cached feature toggle configuration. | 132 | | bootstrapOverride | no| `true` | Should the bootstrap automatically override cached data in the local-storage. Will only be used if bootstrap is not an empty array. | 133 | | headerName | no| `Authorization` | Which header the SDK should use to authorize with Unleash / Unleash Edge. The header will be given the `clientKey` as its value. | 134 | | customHeaders | no| `{}` | Additional headers to use when making HTTP requests to Unleash. In case of name collisions with the default headers, the `customHeaders` value will be used if it is not `null` or `undefined`. `customHeaders` values that are `null` or `undefined` will be ignored. | 135 | | impressionDataAll | no| `false` | Allows you to trigger "impression" events for **all** `getToggle` and `getVariant` invocations. This is particularly useful for "disabled" feature toggles that are not visible to frontend SDKs. | 136 | | environment | no | `default` | Sets the `environment` option of the [Unleash context](https://docs.getunleash.io/reference/unleash-context). This does **not** affect the SDK's [Unleash environment](https://docs.getunleash.io/reference/environments). | 137 | | usePOSTrequests | no | `false` | Configures the client to use POST requests instead of GET when requesting enabled features. This is helpful when sensitive information (like user email, when used as a user ID) is passed in the context to avoid leaking it in the URL. NOTE: Post requests are not supported by the frontend api built into Unleash. | 138 | | experimental | no | `{}` | Enabling optional experimentation. `togglesStorageTTL` : How long (Time To Live), in seconds, the toggles in storage are considered valid and should not be fetched on start. If set to 0 will disable expiration checking and will be considered always expired. | 139 | 140 | ### Listen for updates via the EventEmitter 141 | 142 | The client is also an event emitter. This means that your code can subscribe to updates from the client. 143 | This is a neat way to update a single page app when toggle state updates. 144 | 145 | ```js 146 | unleash.on('update', () => { 147 | const myToggle = unleash.isEnabled('js.demo'); 148 | //do something useful 149 | }); 150 | ``` 151 | 152 | #### Available events: 153 | 154 | - **error** - emitted when an error occurs on init, or when fetch function fails, or when fetch receives a non-ok response object. The error object is sent as payload. 155 | - **initialized** - emitted after the SDK has read local cached data in the storageProvider. 156 | - **ready** - emitted after the SDK has successfully started and performed the initial fetch of flags via the network (Edge, proxy, or front-end API). When bootstrapping, the client can emit this event twice: once when the bootstrapped flags are loaded, and once on first successful connection to Unleash. 157 | - **update** - emitted every time Unleash returns a new feature toggle configuration. The SDK will emit this event as part of the initial fetch from the SDK. 158 | - **recovered** - emitted when the SDK has recovered from an error. This event will only be emitted if the SDK has previously emitted an error. 159 | - **sent** - emitted when the SDK has successfully sent metrics to Unleash. 160 | 161 | > PS! Please remember that you should always register your event listeners before your call `unleash.start()`. If you register them after you have started the SDK you risk loosing important events. 162 | 163 | ### SessionId - Important note! 164 | 165 | You may provide a custom session id via the "context". If you do not provide a sessionId this SDK will create a random session id, which will also be stored in the provided storage (local storage). By always having a consistent sessionId available ensures that even "anonymous" users will get a consistent experience when feature toggles is evaluated, in combination with a gradual (percentage based) rollout. 166 | 167 | ### Stop the SDK 168 | You can stop the Unleash client by calling the `stop` method. Once the client has been stopped, it will no longer check for updates or send metrics to the server. 169 | 170 | A stopped client _can_ be restarted. 171 | 172 | ```js 173 | unleash.stop() 174 | ``` 175 | 176 | ### Custom store 177 | 178 | This SDK can work with React Native storage [@react-native-async-storage/async-storage](https://react-native-async-storage.github.io/async-storage/) or [react-native-shared-preferences](https://github.com/sriraman/react-native-shared-preferences) and many more to backup feature toggles locally. This is useful for bootstrapping the SDK the next time the user comes back to your application. 179 | 180 | You can provide your own storage implementation. 181 | 182 | Examples: 183 | 184 | ```typescript 185 | import SharedPreferences from 'react-native-shared-preferences'; 186 | import { UnleashClient } from 'unleash-proxy-client'; 187 | 188 | const unleash = new UnleashClient({ 189 | url: 'https://eu.unleash-hosted.com/hosted/proxy', 190 | clientKey: 'your-proxy-key', 191 | appName: 'my-webapp', 192 | storageProvider: { 193 | save: (name: string, data: any) => SharedPreferences.setItem(name, data), 194 | get: (name: string) => SharedPreferences.getItem(name, (val) => val) 195 | }, 196 | }); 197 | ``` 198 | 199 | ```typescript 200 | import AsyncStorage from '@react-native-async-storage/async-storage'; 201 | import { UnleashClient } from 'unleash-proxy-client'; 202 | 203 | const PREFIX = 'unleash:repository'; 204 | 205 | const unleash = new UnleashClient({ 206 | url: 'https://eu.unleash-hosted.com/hosted/proxy', 207 | clientKey: 'your-proxy-key', 208 | appName: 'my-webapp', 209 | storageProvider: { 210 | save: (name: string, data: any) => { 211 | const repo = JSON.stringify(data); 212 | const key = `${PREFIX}:${name}`; 213 | return AsyncStorage.setItem(key, repo); 214 | }, 215 | get: (name: string) => { 216 | const key = `${PREFIX}:${name}`; 217 | const data = await AsyncStorage.getItem(key); 218 | return data ? JSON.parse(data) : undefined; 219 | } 220 | }, 221 | }); 222 | ``` 223 | ## How to use in node.js 224 | 225 | This SDK can also be used in node.js applications (from v1.4.0). Please note that you will need to provide a valid "fetch" implementation. Only ECMAScript modules is exported from this package. 226 | 227 | ```js 228 | import fetch from 'node-fetch'; 229 | import { UnleashClient, InMemoryStorageProvider } from 'unleash-proxy-client'; 230 | 231 | const unleash = new UnleashClient({ 232 | url: 'https://app.unleash-hosted.com/demo/proxy', 233 | clientKey: 'proxy-123', 234 | appName: 'nodejs-proxy', 235 | storageProvider: new InMemoryStorageProvider(), 236 | fetch, 237 | }); 238 | 239 | await unleash.start(); 240 | const isEnabled = unleash.isEnabled('proxy.demo'); 241 | console.log(isEnabled); 242 | ``` 243 | *index.mjs* 244 | 245 | ## How to use the client via CDN. 246 | 247 | ```html 248 | 249 | 250 | 251 | 261 | 262 | 263 | ``` 264 | ## Bootstrap 265 | Now it is possible to bootstrap the SDK with your own feature toggle configuration when you don't want to make an API call. 266 | 267 | This is also useful if you require the toggles to be in a certain state immediately after initializing the SDK. 268 | 269 | ### How to use it ? 270 | Add a `bootstrap` attribute when create a new `UnleashClient`. 271 | There's also a `bootstrapOverride` attribute which is by default is `true`. 272 | 273 | ```js 274 | import { UnleashClient } from 'unleash-proxy-client'; 275 | 276 | const unleash = new UnleashClient({ 277 | url: 'https://app.unleash-hosted.com/demo/proxy', 278 | clientKey: 'proxy-123', 279 | appName: 'nodejs-proxy', 280 | bootstrap: [{ 281 | "enabled": true, 282 | "name": "demoApp.step4", 283 | "variant": { 284 | "enabled": true, 285 | "name": "blue", 286 | "feature_enabled": true, 287 | } 288 | }], 289 | bootstrapOverride: false 290 | }); 291 | ``` 292 | **NOTES: ⚠️** 293 | If `bootstrapOverride` is `true` (by default), any local cached data will be overridden with the bootstrap specified. 294 | If `bootstrapOverride` is `false` any local cached data will not be overridden unless the local cache is empty. 295 | 296 | ## Manage your own refresh mechanism 297 | 298 | You can opt out of the Unleash feature flag auto-refresh mechanism and metrics update by settings the `refreshInterval` and/or `metricsInterval` options to `0`. 299 | In this case, it becomes your responsibility to call `updateToggles` and/or `sendMetrics` methods. 300 | This approach is useful in environments that do not support the `setInterval` API, such as service workers. 301 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | ## Examples 2 | 3 | Moved to [unleash-sdk-examples](https://github.com/Unleash/unleash-sdk-examples/tree/main/JavaScript) 4 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | roots: ['/src'], 3 | transform: { 4 | '^.+\\.tsx?$': 'ts-jest', 5 | }, 6 | automock: false, 7 | setupFiles: ['./setupJest.js', 'jest-localstorage-mock'], 8 | testEnvironment: 'jsdom', 9 | }; 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "unleash-proxy-client", 3 | "version": "3.8.0-alpha.0", 4 | "description": "A browser client that can be used together with Unleash Edge or the Unleash Frontend API.", 5 | "type": "module", 6 | "main": "./build/index.cjs", 7 | "types": "./build/cjs/index.d.ts", 8 | "browser": "./build/main.min.js", 9 | "module": "./build/main.esm.js", 10 | "exports": { 11 | ".": { 12 | "import": "./build/main.esm.js", 13 | "node": "./build/index.cjs", 14 | "require": "./build/index.cjs", 15 | "types": "./build/cjs/index.d.ts", 16 | "default": "./build/main.min.js" 17 | } 18 | }, 19 | "files": [ 20 | "build", 21 | "examples", 22 | "src" 23 | ], 24 | "scripts": { 25 | "build": "rm -rf build && rollup -c rollup.config.mjs", 26 | "prepack": "yarn build", 27 | "format": "prettier src --write --loglevel warn", 28 | "lint": "prettier src --check && eslint src", 29 | "test": "jest" 30 | }, 31 | "repository": { 32 | "type": "git", 33 | "url": "git+https://github.com/unleash/unleash-proxy-client-js.git" 34 | }, 35 | "author": "@Unleash", 36 | "license": "Apache-2.0", 37 | "bugs": { 38 | "url": "https://github.com/unleash/unleash-proxy-client-js/issues" 39 | }, 40 | "homepage": "https://github.com/unleash/unleash-proxy-client-js#readme", 41 | "dependencies": { 42 | "tiny-emitter": "^2.1.0", 43 | "uuid": "^9.0.1" 44 | }, 45 | "devDependencies": { 46 | "@babel/runtime": "^7.23.1", 47 | "@rollup/plugin-commonjs": "^25.0.5", 48 | "@rollup/plugin-node-resolve": "^15.2.3", 49 | "@rollup/plugin-replace": "^6.0.2", 50 | "@rollup/plugin-terser": "^0.4.4", 51 | "@rollup/plugin-typescript": "^11.1.5", 52 | "@types/jest": "^29.5.5", 53 | "@types/uuid": "^9.0.5", 54 | "@typescript-eslint/eslint-plugin": "^6.7.5", 55 | "@typescript-eslint/parser": "^6.7.5", 56 | "eslint": "^8.51.0", 57 | "jest": "^29.7.0", 58 | "jest-environment-jsdom": "^29.7.0", 59 | "jest-fetch-mock": "3.0.3", 60 | "jest-localstorage-mock": "^2.4.26", 61 | "prettier": "^3.0.3", 62 | "rollup": "^3.29.4", 63 | "rollup-plugin-node-polyfills": "^0.2.1", 64 | "ts-jest": "^29.1.1", 65 | "tslib": "^2.6.2", 66 | "typescript": "^5.2.2", 67 | "uglify-js": "^3.17.4" 68 | }, 69 | "eslintConfig": { 70 | "env": { 71 | "browser": true, 72 | "es2021": true, 73 | "node": true 74 | }, 75 | "extends": [ 76 | "eslint:recommended", 77 | "plugin:@typescript-eslint/recommended" 78 | ], 79 | "parser": "@typescript-eslint/parser", 80 | "parserOptions": { 81 | "ecmaVersion": "latest", 82 | "sourceType": "module" 83 | }, 84 | "plugins": [ 85 | "@typescript-eslint" 86 | ], 87 | "rules": { 88 | "@typescript-eslint/no-explicit-any": "off" 89 | } 90 | }, 91 | "packageManager": "yarn@1.22.21+sha1.1959a18351b811cdeedbd484a8f86c3cc3bbaf72" 92 | } 93 | -------------------------------------------------------------------------------- /rollup.config.mjs: -------------------------------------------------------------------------------- 1 | import typescript from '@rollup/plugin-typescript'; 2 | import nodeResolve from '@rollup/plugin-node-resolve'; 3 | import commonjs from '@rollup/plugin-commonjs'; 4 | import terser from '@rollup/plugin-terser'; 5 | import nodePolyfills from 'rollup-plugin-node-polyfills'; 6 | import replace from '@rollup/plugin-replace'; 7 | import fs from 'fs'; 8 | 9 | const version = JSON.parse(fs.readFileSync('./package.json', 'UTF-8')).version; 10 | 11 | export default { 12 | input: './src/index.ts', 13 | output: [ 14 | { 15 | file: './build/main.min.js', 16 | format: 'umd', 17 | sourcemap: true, 18 | name: 'unleash', // the global which can be used in a browser 19 | }, 20 | { 21 | file: './build/main.esm.js', 22 | format: 'esm', 23 | sourcemap: true, 24 | }, 25 | { 26 | file: './build/index.cjs', 27 | format: 'cjs', 28 | sourcemap: true, 29 | } 30 | ], 31 | plugins: [ 32 | replace({ 33 | '__VERSION__': version, 34 | preventAssignment: true 35 | }), 36 | typescript({ 37 | compilerOptions: { 38 | lib: ['es5', 'es6', 'dom'], 39 | module: 'ES2015', 40 | target: 'es5', 41 | }, 42 | sourceMap: true, 43 | }), 44 | nodePolyfills(), 45 | nodeResolve({ 46 | browser: true, 47 | }), 48 | commonjs({ 49 | include: 'node_modules/**', 50 | }), 51 | terser(), 52 | ], 53 | }; 54 | -------------------------------------------------------------------------------- /setupJest.js: -------------------------------------------------------------------------------- 1 | global.fetch = require('jest-fetch-mock'); 2 | -------------------------------------------------------------------------------- /src/events-handler.ts: -------------------------------------------------------------------------------- 1 | import { IContext } from '.'; 2 | import { v4 as uuidv4 } from 'uuid'; 3 | 4 | class EventsHandler { 5 | private generateEventId() { 6 | return uuidv4(); 7 | } 8 | 9 | public createImpressionEvent( 10 | context: IContext, 11 | enabled: boolean, 12 | featureName: string, 13 | eventType: string, 14 | impressionData?: boolean, 15 | variant?: string 16 | ) { 17 | const baseEvent = this.createBaseEvent( 18 | context, 19 | enabled, 20 | featureName, 21 | eventType, 22 | impressionData 23 | ); 24 | 25 | if (variant) { 26 | return { 27 | ...baseEvent, 28 | variant, 29 | }; 30 | } 31 | return baseEvent; 32 | } 33 | 34 | private createBaseEvent( 35 | context: IContext, 36 | enabled: boolean, 37 | featureName: string, 38 | eventType: string, 39 | impressionData?: boolean 40 | ) { 41 | return { 42 | eventType, 43 | eventId: this.generateEventId(), 44 | context, 45 | enabled, 46 | featureName, 47 | impressionData, 48 | }; 49 | } 50 | } 51 | 52 | export default EventsHandler; 53 | -------------------------------------------------------------------------------- /src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { FetchMock } from 'jest-fetch-mock'; 2 | import 'jest-localstorage-mock'; 3 | import * as data from './test/testdata.json'; 4 | import IStorageProvider from './storage-provider'; 5 | import { 6 | EVENTS, 7 | IConfig, 8 | IMutableContext, 9 | IToggle, 10 | InMemoryStorageProvider, 11 | UnleashClient, 12 | lastUpdateKey, 13 | } from './index'; 14 | import { getTypeSafeRequest, getTypeSafeRequestUrl } from './test'; 15 | import Metrics from './metrics'; 16 | 17 | jest.useFakeTimers(); 18 | 19 | const fetchMock = fetch as FetchMock; 20 | 21 | afterEach(() => { 22 | fetchMock.resetMocks(); 23 | jest.clearAllTimers(); 24 | }); 25 | 26 | test('Should initialize unleash-client', () => { 27 | const config: IConfig = { 28 | url: 'http://localhost/test', 29 | clientKey: '12', 30 | appName: 'web', 31 | }; 32 | new UnleashClient(config); 33 | expect(config.url).toBe('http://localhost/test'); 34 | }); 35 | 36 | test('Should perform an initial fetch', async () => { 37 | fetchMock.mockResponseOnce(JSON.stringify(data)); 38 | const config: IConfig = { 39 | url: 'http://localhost/test', 40 | clientKey: '12', 41 | appName: 'web', 42 | }; 43 | const client = new UnleashClient(config); 44 | await client.start(); 45 | const isEnabled = client.isEnabled('simpleToggle'); 46 | client.stop(); 47 | expect(isEnabled).toBe(true); 48 | }); 49 | 50 | test('Should perform an initial fetch as POST', async () => { 51 | fetchMock.mockResponseOnce(JSON.stringify(data)); 52 | const config: IConfig = { 53 | url: 'http://localhost/test', 54 | clientKey: '12', 55 | appName: 'webAsPOST', 56 | usePOSTrequests: true, 57 | }; 58 | const client = new UnleashClient(config); 59 | await client.start(); 60 | 61 | const request = getTypeSafeRequest(fetchMock, 0); 62 | const body = JSON.parse(request.body as string); 63 | 64 | expect(request.method).toBe('POST'); 65 | expect(body.context.appName).toBe('webAsPOST'); 66 | expect(request.headers).toMatchObject({ 67 | 'content-type': 'application/json', 68 | }); 69 | }); 70 | 71 | test('Should perform an initial fetch as GET', async () => { 72 | fetchMock.mockResponseOnce(JSON.stringify(data)); 73 | const config: IConfig = { 74 | url: 'http://localhost/test', 75 | clientKey: '12', 76 | appName: 'webAsGET', 77 | }; 78 | const client = new UnleashClient(config); 79 | await client.start(); 80 | 81 | const request = getTypeSafeRequest(fetchMock, 0); 82 | 83 | expect(request.method).toBe('GET'); 84 | expect(request.headers).not.toMatchObject({ 85 | 'Content-Type': 'application/json', 86 | }); 87 | }); 88 | 89 | test('Should have correct variant', async () => { 90 | fetchMock.mockResponseOnce(JSON.stringify(data)); 91 | const config: IConfig = { 92 | url: 'http://localhost/test', 93 | clientKey: '12', 94 | appName: 'web', 95 | }; 96 | const client = new UnleashClient(config); 97 | await client.start(); 98 | const variant = client.getVariant('variantToggle'); 99 | const payload = variant.payload || { type: 'undef', value: '' }; 100 | client.stop(); 101 | expect(variant.name).toBe('green'); 102 | expect(variant.enabled).toBe(true); 103 | expect(variant.feature_enabled).toBe(true); 104 | expect(payload.type).toBe('string'); 105 | expect(payload.value).toBe('some-text'); 106 | }); 107 | 108 | test('Should return default variant if not found', async () => { 109 | fetchMock.mockResponseOnce(JSON.stringify(data)); 110 | const config: IConfig = { 111 | url: 'http://localhost/test', 112 | clientKey: '12', 113 | appName: 'web', 114 | }; 115 | const client = new UnleashClient(config); 116 | await client.start(); 117 | const variant = client.getVariant('missingToggle'); 118 | const payload = variant.payload || { type: 'undef', value: '' }; 119 | client.stop(); 120 | expect(variant.name).toBe('disabled'); 121 | expect(variant.enabled).toBe(false); 122 | expect(variant.feature_enabled).toBe(false); 123 | expect(payload.type).toBe('undef'); 124 | expect(payload.value).toBe(''); 125 | }); 126 | 127 | test('Should handle error and return false for isEnabled', async () => { 128 | jest.spyOn(global.console, 'error').mockImplementation(() => jest.fn()); 129 | fetchMock.mockReject(); 130 | 131 | class Store implements IStorageProvider { 132 | public async save() { 133 | return Promise.resolve(); 134 | } 135 | 136 | public async get() { 137 | return Promise.resolve([]); 138 | } 139 | } 140 | 141 | const storageProvider = new Store(); 142 | const config: IConfig = { 143 | url: 'http://localhost/test', 144 | clientKey: '12', 145 | appName: 'web', 146 | storageProvider, 147 | }; 148 | const client = new UnleashClient(config); 149 | await client.start(); 150 | const isEnabled = client.isEnabled('simpleToggle'); 151 | client.stop(); 152 | expect(isEnabled).toBe(false); 153 | }); 154 | 155 | test('Should read session id from localStorage', async () => { 156 | const sessionId = '123'; 157 | fetchMock.mockReject(); 158 | 159 | class Store implements IStorageProvider { 160 | public async save() { 161 | return Promise.resolve(); 162 | } 163 | 164 | public async get(name: string) { 165 | if (name === 'sessionId') { 166 | return sessionId; 167 | } 168 | return Promise.resolve([]); 169 | } 170 | } 171 | 172 | const storageProvider = new Store(); 173 | const config: IConfig = { 174 | url: 'http://localhost/test', 175 | clientKey: '12', 176 | appName: 'web', 177 | storageProvider, 178 | }; 179 | const client = new UnleashClient(config); 180 | await client.start(); 181 | const context = client.getContext(); 182 | expect(context.sessionId).toBe(sessionId); 183 | }); 184 | 185 | test('Should send sessionId as string, even if it was saved a number', async () => { 186 | const sessionId = 123; 187 | fetchMock.mockReject(); 188 | 189 | class Store implements IStorageProvider { 190 | public async save() { 191 | return Promise.resolve(); 192 | } 193 | 194 | public async get(name: string) { 195 | if (name === 'sessionId') { 196 | return sessionId; 197 | } 198 | return Promise.resolve([]); 199 | } 200 | } 201 | 202 | const storageProvider = new Store(); 203 | const config: IConfig = { 204 | url: 'http://localhost/test', 205 | clientKey: '12', 206 | appName: 'web', 207 | storageProvider, 208 | }; 209 | const client = new UnleashClient(config); 210 | await client.start(); 211 | const context = client.getContext(); 212 | expect(context.sessionId).toBe('123'); 213 | }); 214 | test('Should read toggles from localStorage', async () => { 215 | jest.spyOn(global.console, 'error').mockImplementation(() => jest.fn()); 216 | const toggles = [ 217 | { 218 | name: 'featureToggleBackup', 219 | enabled: true, 220 | variant: { 221 | name: 'disabled', 222 | enabled: false, 223 | feature_enabled: true, 224 | }, 225 | }, 226 | ]; 227 | fetchMock.mockReject(); 228 | 229 | class Store implements IStorageProvider { 230 | public async save() { 231 | return Promise.resolve(); 232 | } 233 | 234 | public async get(name: string) { 235 | if (name === 'repo') { 236 | return Promise.resolve(toggles); 237 | } else { 238 | return Promise.resolve(undefined); 239 | } 240 | } 241 | } 242 | 243 | const storageProvider = new Store(); 244 | const config: IConfig = { 245 | url: 'http://localhost/test', 246 | clientKey: '12', 247 | appName: 'web', 248 | storageProvider, 249 | }; 250 | const client = new UnleashClient(config); 251 | await client.start(); 252 | expect(client.isEnabled('featureToggleBackup')).toBe(true); 253 | expect(client.isEnabled('featureUnknown')).toBe(false); 254 | }); 255 | 256 | test('Should bootstrap data when bootstrap is provided', async () => { 257 | localStorage.clear(); 258 | const storeKey = 'unleash:repository:repo'; 259 | const bootstrap = [ 260 | { 261 | name: 'toggles', 262 | enabled: true, 263 | variant: { 264 | name: 'disabled', 265 | enabled: false, 266 | feature_enabled: true, 267 | }, 268 | impressionData: true, 269 | }, 270 | { 271 | name: 'algo', 272 | enabled: true, 273 | variant: { 274 | name: 'disabled', 275 | enabled: false, 276 | feature_enabled: true, 277 | }, 278 | impressionData: true, 279 | }, 280 | ]; 281 | const initialData = [ 282 | { 283 | name: 'initialData', 284 | enabled: true, 285 | variant: { 286 | name: 'disabled', 287 | enabled: false, 288 | feature_enabled: true, 289 | }, 290 | impressionData: true, 291 | }, 292 | { 293 | name: 'test initial', 294 | enabled: true, 295 | variant: { 296 | name: 'disabled', 297 | enabled: false, 298 | feature_enabled: true, 299 | }, 300 | impressionData: true, 301 | }, 302 | ]; 303 | 304 | localStorage.setItem(storeKey, JSON.stringify(initialData)); 305 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(initialData)); 306 | 307 | const config: IConfig = { 308 | url: 'http://localhost/test', 309 | clientKey: '12', 310 | appName: 'web', 311 | bootstrap, 312 | }; 313 | const client = new UnleashClient(config); 314 | await client.start(); 315 | 316 | expect(client.getAllToggles()).toStrictEqual(bootstrap); 317 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(bootstrap)); 318 | }); 319 | 320 | it('should return correct variant if called asynchronously multiple times', async () => { 321 | const bootstrap = [ 322 | { 323 | name: 'foo', 324 | enabled: true, 325 | variant: { 326 | name: 'A', 327 | enabled: true, 328 | payload: { 329 | type: 'string', 330 | value: 'FOO', 331 | }, 332 | }, 333 | impressionData: false, 334 | }, 335 | ]; 336 | 337 | const config: IConfig = { 338 | url: 'http://localhost/test', 339 | clientKey: '12', 340 | appName: 'web', 341 | refreshInterval: 0, 342 | metricsInterval: 0, 343 | disableRefresh: true, 344 | bootstrapOverride: true, 345 | bootstrap, 346 | createAbortController: () => null, 347 | }; 348 | const client = new UnleashClient(config); 349 | 350 | for (let i = 0; i < 12; i++) { 351 | await true; 352 | 353 | expect(client.getVariant('foo')).toEqual({ 354 | name: 'A', 355 | enabled: true, 356 | feature_enabled: true, 357 | payload: { 358 | type: 'string', 359 | value: 'FOO', 360 | }, 361 | }); 362 | } 363 | }); 364 | 365 | test('Should set internal toggle state when bootstrap is set, before client is started', async () => { 366 | localStorage.clear(); 367 | const storeKey = 'unleash:repository:repo'; 368 | const bootstrap = [ 369 | { 370 | name: 'toggles', 371 | enabled: true, 372 | variant: { 373 | name: 'disabled', 374 | enabled: false, 375 | feature_enabled: true, 376 | }, 377 | impressionData: true, 378 | }, 379 | { 380 | name: 'algo', 381 | enabled: true, 382 | variant: { 383 | name: 'disabled', 384 | enabled: false, 385 | feature_enabled: true, 386 | }, 387 | impressionData: true, 388 | }, 389 | ]; 390 | const initialData = [ 391 | { 392 | name: 'initialData', 393 | enabled: true, 394 | variant: { 395 | name: 'disabled', 396 | enabled: false, 397 | feature_enabled: true, 398 | }, 399 | impressionData: true, 400 | }, 401 | { 402 | name: 'test initial', 403 | enabled: true, 404 | variant: { 405 | name: 'disabled', 406 | enabled: false, 407 | feature_enabled: true, 408 | }, 409 | impressionData: true, 410 | }, 411 | ]; 412 | 413 | localStorage.setItem(storeKey, JSON.stringify(initialData)); 414 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(initialData)); 415 | 416 | const config: IConfig = { 417 | url: 'http://localhost/test', 418 | clientKey: '12', 419 | appName: 'web', 420 | bootstrap, 421 | }; 422 | const client = new UnleashClient(config); 423 | expect(client.getAllToggles()).toStrictEqual(bootstrap); 424 | await client.start(); 425 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(bootstrap)); 426 | }); 427 | 428 | test('Should not bootstrap data when bootstrapOverride is false and localStorage is not empty', async () => { 429 | localStorage.clear(); 430 | const storeKey = 'unleash:repository:repo'; 431 | const bootstrap = [ 432 | { 433 | name: 'toggles', 434 | enabled: true, 435 | variant: { 436 | name: 'disabled', 437 | enabled: false, 438 | feature_enabled: true, 439 | }, 440 | impressionData: true, 441 | }, 442 | { 443 | name: 'algo', 444 | enabled: true, 445 | variant: { 446 | name: 'disabled', 447 | enabled: false, 448 | feature_enabled: true, 449 | }, 450 | impressionData: true, 451 | }, 452 | ]; 453 | const initialData = [ 454 | { 455 | name: 'initialData', 456 | enabled: true, 457 | variant: { 458 | name: 'disabled', 459 | enabled: false, 460 | feature_enabled: true, 461 | }, 462 | impressionData: true, 463 | }, 464 | { 465 | name: 'test initial', 466 | enabled: true, 467 | variant: { 468 | name: 'disabled', 469 | enabled: false, 470 | feature_enabled: true, 471 | }, 472 | impressionData: true, 473 | }, 474 | ]; 475 | 476 | localStorage.setItem(storeKey, JSON.stringify(initialData)); 477 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(initialData)); 478 | 479 | const config: IConfig = { 480 | url: 'http://localhost/test', 481 | clientKey: '12', 482 | appName: 'web', 483 | bootstrap, 484 | bootstrapOverride: false, 485 | }; 486 | const client = new UnleashClient(config); 487 | await client.start(); 488 | 489 | expect(client.getAllToggles()).toStrictEqual(initialData); 490 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(initialData)); 491 | }); 492 | 493 | test('Should bootstrap when bootstrapOverride is false and local storage is empty', async () => { 494 | localStorage.clear(); 495 | const storeKey = 'unleash:repository:repo'; 496 | const bootstrap = [ 497 | { 498 | name: 'toggles', 499 | enabled: true, 500 | variant: { 501 | name: 'disabled', 502 | enabled: false, 503 | feature_enabled: true, 504 | }, 505 | impressionData: true, 506 | }, 507 | { 508 | name: 'algo', 509 | enabled: true, 510 | variant: { 511 | name: 'disabled', 512 | enabled: false, 513 | feature_enabled: true, 514 | }, 515 | impressionData: true, 516 | }, 517 | ]; 518 | 519 | localStorage.setItem(storeKey, JSON.stringify([])); 520 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify([])); 521 | 522 | const config: IConfig = { 523 | url: 'http://localhost/test', 524 | clientKey: '12', 525 | appName: 'web', 526 | bootstrap, 527 | bootstrapOverride: false, 528 | }; 529 | const client = new UnleashClient(config); 530 | await client.start(); 531 | 532 | expect(client.getAllToggles()).toStrictEqual(bootstrap); 533 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(bootstrap)); 534 | }); 535 | 536 | test('Should not bootstrap data when bootstrap is []', async () => { 537 | localStorage.clear(); 538 | const storeKey = 'unleash:repository:repo'; 539 | const initialData = [ 540 | { 541 | name: 'initialData', 542 | enabled: true, 543 | variant: { 544 | name: 'disabled', 545 | enabled: false, 546 | feature_enabled: true, 547 | }, 548 | }, 549 | { 550 | name: 'test initial', 551 | enabled: true, 552 | variant: { 553 | name: 'disabled', 554 | enabled: false, 555 | feature_enabled: true, 556 | }, 557 | }, 558 | ]; 559 | 560 | localStorage.setItem(storeKey, JSON.stringify(initialData)); 561 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(initialData)); 562 | 563 | const config: IConfig = { 564 | url: 'http://localhost/test', 565 | clientKey: '12', 566 | appName: 'web', 567 | bootstrap: [], 568 | bootstrapOverride: true, 569 | }; 570 | const client = new UnleashClient(config); 571 | await client.start(); 572 | 573 | expect(client.getAllToggles()).toStrictEqual(initialData); 574 | expect(localStorage.getItem(storeKey)).toBe(JSON.stringify(initialData)); 575 | }); 576 | 577 | test('Should publish ready event when bootstrap is provided, before client is started', async () => { 578 | localStorage.clear(); 579 | const bootstrap = [ 580 | { 581 | name: 'toggles', 582 | enabled: true, 583 | variant: { 584 | name: 'disabled', 585 | enabled: false, 586 | feature_enabled: true, 587 | }, 588 | impressionData: true, 589 | }, 590 | { 591 | name: 'algo', 592 | enabled: true, 593 | variant: { 594 | name: 'disabled', 595 | enabled: false, 596 | feature_enabled: true, 597 | }, 598 | impressionData: true, 599 | }, 600 | ]; 601 | 602 | const config: IConfig = { 603 | url: 'http://localhost/test', 604 | clientKey: '12', 605 | appName: 'web', 606 | bootstrap, 607 | }; 608 | const client = new UnleashClient(config); 609 | expect(client.getAllToggles()).toStrictEqual(bootstrap); 610 | client.on(EVENTS.READY, () => { 611 | expect(client.isEnabled('algo')).toBe(true); 612 | }); 613 | }); 614 | 615 | test('Should publish ready when initial fetch completed', (done) => { 616 | fetchMock.mockResponseOnce(JSON.stringify(data)); 617 | const config: IConfig = { 618 | url: 'http://localhost/test', 619 | clientKey: '12', 620 | appName: 'web', 621 | }; 622 | const client = new UnleashClient(config); 623 | client.start(); 624 | client.on(EVENTS.READY, () => { 625 | const isEnabled = client.isEnabled('simpleToggle'); 626 | client.stop(); 627 | expect(isEnabled).toBe(true); 628 | done(); 629 | }); 630 | }); 631 | 632 | test('Should publish error when initial init fails', (done) => { 633 | const givenError = 'Error'; 634 | 635 | class Store implements IStorageProvider { 636 | public async save(): Promise { 637 | return Promise.reject(givenError); 638 | } 639 | 640 | public async get(): Promise { 641 | return Promise.reject(givenError); 642 | } 643 | } 644 | 645 | jest.spyOn(global.console, 'error').mockImplementation(() => jest.fn()); 646 | fetchMock.mockResponseOnce(JSON.stringify(data)); 647 | 648 | const storageProvider = new Store(); 649 | const config: IConfig = { 650 | url: 'http://localhost/test', 651 | clientKey: '12', 652 | appName: 'web', 653 | storageProvider, 654 | }; 655 | const client = new UnleashClient(config); 656 | client.start(); 657 | client.on(EVENTS.ERROR, (e: any) => { 658 | expect(e).toBe(givenError); 659 | done(); 660 | }); 661 | }); 662 | 663 | test('Should publish error when fetch fails', (done) => { 664 | const givenError = new Error('Error'); 665 | 666 | jest.spyOn(global.console, 'error').mockImplementation(() => jest.fn()); 667 | fetchMock.mockReject(givenError); 668 | 669 | const config: IConfig = { 670 | url: 'http://localhost/test', 671 | clientKey: '12', 672 | appName: 'web', 673 | }; 674 | const client = new UnleashClient(config); 675 | client.start(); 676 | client.on(EVENTS.ERROR, (e: any) => { 677 | expect(e).toBe(givenError); 678 | done(); 679 | }); 680 | }); 681 | 682 | test('Should abort previous request', async () => { 683 | fetchMock.mockResponse(JSON.stringify(data)); 684 | const abortSpy = jest.spyOn(AbortController.prototype, 'abort'); 685 | 686 | const config: IConfig = { 687 | url: 'http://localhost/test', 688 | clientKey: '12', 689 | appName: 'web', 690 | }; 691 | const client = new UnleashClient(config); 692 | 693 | await client.start(); 694 | client.updateContext({ userId: '123' }); // abort 1 695 | client.updateContext({ userId: '456' }); // abort 2 696 | await client.updateContext({ userId: '789' }); 697 | 698 | expect(abortSpy).toHaveBeenCalledTimes(2); 699 | abortSpy.mockRestore(); 700 | }); 701 | 702 | test('Should not trigger error on abort', async () => { 703 | fetchMock.mockResponse(JSON.stringify(data)); 704 | 705 | const config: IConfig = { 706 | url: 'http://localhost/test', 707 | clientKey: '12', 708 | appName: 'web', 709 | }; 710 | const client = new UnleashClient(config); 711 | client.on(EVENTS.ERROR, () => { 712 | throw new Error('abort should not trigger error'); 713 | }); 714 | 715 | await client.start(); 716 | 717 | fetchMock.mockAbort(); 718 | await client.updateContext({ userId: '789' }); 719 | }); 720 | 721 | test('Should run without abort controller', async () => { 722 | fetchMock.mockResponse(JSON.stringify(data)); 723 | const abortSpy = jest.spyOn(AbortController.prototype, 'abort'); 724 | 725 | const config: IConfig = { 726 | url: 'http://localhost/test', 727 | clientKey: '12', 728 | appName: 'web', 729 | createAbortController: () => null, 730 | }; 731 | const client = new UnleashClient(config); 732 | 733 | await client.start(); 734 | client.updateContext({ userId: '123' }); 735 | client.updateContext({ userId: '456' }); 736 | await client.updateContext({ userId: '789' }); 737 | 738 | expect(abortSpy).toHaveBeenCalledTimes(0); 739 | abortSpy.mockRestore(); 740 | }); 741 | 742 | test.each([400, 401, 403, 404, 429, 500, 502, 503])( 743 | 'Should publish error when fetch receives a %d error', 744 | async (errorCode) => { 745 | expect.assertions(1); 746 | jest.spyOn(global.console, 'error').mockImplementation(() => jest.fn()); 747 | fetchMock.mockResponseOnce('{}', { status: errorCode }); 748 | 749 | const config: IConfig = { 750 | url: 'http://localhost/test', 751 | clientKey: '12', 752 | appName: 'web', 753 | }; 754 | const client = new UnleashClient(config); 755 | client.on(EVENTS.ERROR, (e: any) => { 756 | expect(e).toStrictEqual({ type: 'HttpError', code: errorCode }); 757 | }); 758 | await client.start(); 759 | } 760 | ); 761 | 762 | test('Should publish update when state changes after refreshInterval', async () => { 763 | expect.assertions(1); 764 | fetchMock.mockResponses( 765 | [JSON.stringify(data), { status: 200 }], 766 | [JSON.stringify(data), { status: 200 }] 767 | ); 768 | const config: IConfig = { 769 | url: 'http://localhost/test', 770 | clientKey: '12', 771 | refreshInterval: 1, 772 | appName: 'web', 773 | }; 774 | const client = new UnleashClient(config); 775 | 776 | let counts = 0; 777 | client.on(EVENTS.UPDATE, () => { 778 | counts++; 779 | if (counts === 2) { 780 | expect(fetchMock.mock.calls.length).toEqual(2); 781 | client.stop(); 782 | } 783 | }); 784 | 785 | await client.start(); 786 | 787 | jest.advanceTimersByTime(1001); 788 | }); 789 | 790 | test(`If refresh is disabled should not fetch`, async () => { 791 | fetchMock.mockResponses( 792 | [JSON.stringify(data), { status: 200 }], 793 | [JSON.stringify(data), { status: 200 }] 794 | ); 795 | const config: IConfig = { 796 | disableRefresh: true, 797 | url: 'http://localhost/test', 798 | clientKey: '12', 799 | refreshInterval: 1, 800 | appName: 'web', 801 | }; 802 | const client = new UnleashClient(config); 803 | await client.start(); 804 | jest.advanceTimersByTime(100000); 805 | expect(fetchMock.mock.calls.length).toEqual(1); // Never called again 806 | }); 807 | 808 | test('Should include etag in second request', async () => { 809 | const etag = '123a'; 810 | fetchMock.mockResponses( 811 | [JSON.stringify(data), { status: 200, headers: { ETag: etag } }], 812 | [JSON.stringify(data), { status: 304, headers: { ETag: etag } }] 813 | ); 814 | const config: IConfig = { 815 | url: 'http://localhost/test', 816 | clientKey: '12', 817 | refreshInterval: 1, 818 | appName: 'web', 819 | }; 820 | const client = new UnleashClient(config); 821 | 822 | await client.start(); 823 | 824 | jest.advanceTimersByTime(1001); 825 | 826 | const firstRequest = getTypeSafeRequest(fetchMock, 0); 827 | const secondRequest = getTypeSafeRequest(fetchMock, 1); 828 | 829 | expect(firstRequest.headers).toMatchObject({}); 830 | expect(secondRequest.headers).toMatchObject({ 831 | 'if-none-match': etag, 832 | }); 833 | }); 834 | 835 | test('Should add clientKey as Authorization header', async () => { 836 | fetchMock.mockResponses( 837 | [JSON.stringify(data), { status: 200 }], 838 | [JSON.stringify(data), { status: 200 }] 839 | ); 840 | const config: IConfig = { 841 | url: 'http://localhost/test', 842 | clientKey: 'some123key', 843 | appName: 'web', 844 | }; 845 | const client = new UnleashClient(config); 846 | await client.start(); 847 | 848 | jest.advanceTimersByTime(1001); 849 | 850 | const request = getTypeSafeRequest(fetchMock); 851 | 852 | expect(request.headers).toMatchObject({ 853 | authorization: 'some123key', 854 | }); 855 | }); 856 | 857 | test('Should require appName', () => { 858 | expect(() => { 859 | new UnleashClient({ 860 | url: 'http://localhost/test', 861 | clientKey: '12', 862 | appName: '', 863 | }); 864 | }).toThrow(); 865 | }); 866 | 867 | test('Should require url', () => { 868 | expect(() => { 869 | new UnleashClient({ url: '', clientKey: '12', appName: 'web' }); 870 | }).toThrow(); 871 | }); 872 | 873 | test('Should require valid url', () => { 874 | expect(() => { 875 | new UnleashClient({ 876 | url: 'not-a-url', 877 | clientKey: '12', 878 | appName: 'web', 879 | }); 880 | }).toThrow(); 881 | }); 882 | 883 | test('Should require valid clientKey', () => { 884 | expect(() => { 885 | new UnleashClient({ 886 | url: 'http://localhost/test', 887 | clientKey: '', 888 | appName: 'web', 889 | }); 890 | }).toThrow(); 891 | }); 892 | 893 | test('Should stop fetching when stop is called', async () => { 894 | fetchMock.mockResponses( 895 | [JSON.stringify(data), { status: 200 }], 896 | [JSON.stringify(data), { status: 200 }], 897 | [JSON.stringify(data), { status: 200 }] 898 | ); 899 | const config: IConfig = { 900 | url: 'http://localhost/test', 901 | clientKey: '12', 902 | refreshInterval: 1, 903 | appName: 'web', 904 | }; 905 | const client = new UnleashClient(config); 906 | 907 | await client.start(); 908 | 909 | jest.advanceTimersByTime(1001); 910 | 911 | client.stop(); 912 | 913 | jest.advanceTimersByTime(1001); 914 | jest.advanceTimersByTime(1001); 915 | jest.advanceTimersByTime(1001); 916 | 917 | expect(fetchMock.mock.calls.length).toEqual(2); 918 | }); 919 | 920 | test('Should include context fields on request', async () => { 921 | fetchMock.mockResponses( 922 | [JSON.stringify(data), { status: 200 }], 923 | [JSON.stringify(data), { status: 304 }] 924 | ); 925 | const context: IMutableContext = { 926 | userId: '123', 927 | sessionId: '456', 928 | remoteAddress: 'address', 929 | properties: { 930 | property1: 'property1', 931 | property2: 'property2', 932 | }, 933 | }; 934 | const config: IConfig = { 935 | url: 'http://localhost/test', 936 | clientKey: '12', 937 | appName: 'web', 938 | environment: 'prod', 939 | context, 940 | }; 941 | const client = new UnleashClient(config); 942 | 943 | await client.start(); 944 | 945 | jest.advanceTimersByTime(1001); 946 | 947 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 948 | 949 | expect(url.searchParams.get('userId')).toEqual('123'); 950 | expect(url.searchParams.get('sessionId')).toEqual('456'); 951 | expect(url.searchParams.get('remoteAddress')).toEqual('address'); 952 | expect(url.searchParams.get('properties[property1]')).toEqual('property1'); 953 | expect(url.searchParams.get('properties[property2]')).toEqual('property2'); 954 | expect(url.searchParams.get('appName')).toEqual('web'); 955 | expect(url.searchParams.get('environment')).toEqual('prod'); 956 | }); 957 | 958 | test('Should note include context fields with "null" value', async () => { 959 | fetchMock.mockResponses( 960 | [JSON.stringify(data), { status: 200 }], 961 | [JSON.stringify(data), { status: 304 }] 962 | ); 963 | const context: IMutableContext = { 964 | userId: undefined, 965 | sessionId: '0', 966 | remoteAddress: undefined, 967 | properties: { 968 | property1: 'property1', 969 | property2: 'property2', 970 | }, 971 | }; 972 | const config: IConfig = { 973 | url: 'http://localhost/test', 974 | clientKey: '12', 975 | appName: 'web', 976 | environment: 'prod', 977 | context, 978 | }; 979 | const client = new UnleashClient(config); 980 | 981 | await client.start(); 982 | 983 | jest.advanceTimersByTime(1001); 984 | 985 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 986 | 987 | expect(url.searchParams.has('userId')).toBe(false); 988 | expect(url.searchParams.has('remoteAddress')).toBe(false); 989 | expect(url.searchParams.has('sessionId')).toBe(true); 990 | expect(url.searchParams.get('sessionId')).toBe('0'); 991 | }); 992 | 993 | test('Should update context fields with await', async () => { 994 | fetchMock.mockResponses( 995 | [JSON.stringify(data), { status: 200 }], 996 | [JSON.stringify(data), { status: 304 }] 997 | ); 998 | const config: IConfig = { 999 | url: 'http://localhost/test', 1000 | clientKey: '12', 1001 | appName: 'web', 1002 | environment: 'prod', 1003 | }; 1004 | const client = new UnleashClient(config); 1005 | await client.updateContext({ 1006 | userId: '123', 1007 | sessionId: '456', 1008 | remoteAddress: 'address', 1009 | properties: { 1010 | property1: 'property1', 1011 | property2: 'property2', 1012 | }, 1013 | }); 1014 | 1015 | await client.start(); 1016 | 1017 | jest.advanceTimersByTime(1001); 1018 | 1019 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 1020 | 1021 | expect(url.searchParams.get('userId')).toEqual('123'); 1022 | expect(url.searchParams.get('sessionId')).toEqual('456'); 1023 | expect(url.searchParams.get('remoteAddress')).toEqual('address'); 1024 | expect(url.searchParams.get('properties[property1]')).toEqual('property1'); 1025 | expect(url.searchParams.get('properties[property2]')).toEqual('property2'); 1026 | expect(url.searchParams.get('appName')).toEqual('web'); 1027 | expect(url.searchParams.get('environment')).toEqual('prod'); 1028 | }); 1029 | 1030 | test('Should update context fields on request', async () => { 1031 | fetchMock.mockResponses( 1032 | [JSON.stringify(data), { status: 200 }], 1033 | [JSON.stringify(data), { status: 304 }] 1034 | ); 1035 | const config: IConfig = { 1036 | url: 'http://localhost/test', 1037 | clientKey: '12', 1038 | appName: 'web', 1039 | environment: 'prod', 1040 | }; 1041 | const client = new UnleashClient(config); 1042 | client.updateContext({ 1043 | userId: '123', 1044 | sessionId: '456', 1045 | remoteAddress: 'address', 1046 | properties: { 1047 | property1: 'property1', 1048 | property2: 'property2', 1049 | }, 1050 | }); 1051 | 1052 | await client.start(); 1053 | 1054 | jest.advanceTimersByTime(1001); 1055 | 1056 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 1057 | 1058 | expect(url.searchParams.get('userId')).toEqual('123'); 1059 | expect(url.searchParams.get('sessionId')).toEqual('456'); 1060 | expect(url.searchParams.get('remoteAddress')).toEqual('address'); 1061 | expect(url.searchParams.get('properties[property1]')).toEqual('property1'); 1062 | expect(url.searchParams.get('properties[property2]')).toEqual('property2'); 1063 | expect(url.searchParams.get('appName')).toEqual('web'); 1064 | expect(url.searchParams.get('environment')).toEqual('prod'); 1065 | }); 1066 | 1067 | test('Updating context should wait on asynchronous start', async () => { 1068 | fetchMock.mockResponses( 1069 | [JSON.stringify(data), { status: 200 }], 1070 | [JSON.stringify(data), { status: 200 }] 1071 | ); 1072 | const config: IConfig = { 1073 | url: 'http://localhost/test', 1074 | clientKey: '12', 1075 | appName: 'web', 1076 | environment: 'prod', 1077 | }; 1078 | const client = new UnleashClient(config); 1079 | 1080 | client.start(); 1081 | await client.updateContext({ 1082 | userId: '123', 1083 | }); 1084 | 1085 | expect(fetchMock).toHaveBeenCalledTimes(2); 1086 | }); 1087 | 1088 | test('Should not replace sessionId when updating context', async () => { 1089 | fetchMock.mockResponses( 1090 | [JSON.stringify(data), { status: 200 }], 1091 | [JSON.stringify(data), { status: 304 }] 1092 | ); 1093 | const config: IConfig = { 1094 | url: 'http://localhost/test', 1095 | clientKey: '12', 1096 | appName: 'web', 1097 | environment: 'prod', 1098 | }; 1099 | const client = new UnleashClient(config); 1100 | await client.start(); 1101 | const context = client.getContext(); 1102 | await client.updateContext({ 1103 | userId: '123', 1104 | remoteAddress: 'address', 1105 | properties: { 1106 | property1: 'property1', 1107 | property2: 'property2', 1108 | }, 1109 | }); 1110 | 1111 | jest.advanceTimersByTime(1001); 1112 | 1113 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 1114 | 1115 | expect(url.searchParams.get('sessionId')).toEqual( 1116 | context.sessionId?.toString() 1117 | ); 1118 | }); 1119 | 1120 | test('Should not add property fields when properties is an empty object', async () => { 1121 | fetchMock.mockResponses( 1122 | [JSON.stringify(data), { status: 200 }], 1123 | [JSON.stringify(data), { status: 304 }] 1124 | ); 1125 | const config: IConfig = { 1126 | url: 'http://localhost/test', 1127 | clientKey: '12', 1128 | appName: 'web', 1129 | environment: 'prod', 1130 | context: { 1131 | properties: {}, 1132 | }, 1133 | }; 1134 | const client = new UnleashClient(config); 1135 | 1136 | await client.start(); 1137 | 1138 | jest.advanceTimersByTime(1001); 1139 | 1140 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 1141 | 1142 | // console.log(url.toString(), url.searchParams.toString(), url.searchParams.get('properties')); 1143 | 1144 | expect(url.searchParams.get('appName')).toEqual('web'); 1145 | expect(url.searchParams.get('environment')).toEqual('prod'); 1146 | expect(url.searchParams.get('properties')).toBeNull(); 1147 | }); 1148 | 1149 | test('Should use default environment', async () => { 1150 | fetchMock.mockResponses( 1151 | [JSON.stringify(data), { status: 200 }], 1152 | [JSON.stringify(data), { status: 200 }] 1153 | ); 1154 | const config: IConfig = { 1155 | url: 'http://localhost/test', 1156 | clientKey: '12', 1157 | appName: 'web', 1158 | }; 1159 | const client = new UnleashClient(config); 1160 | await client.start(); 1161 | 1162 | jest.advanceTimersByTime(1001); 1163 | 1164 | const url = new URL(getTypeSafeRequestUrl(fetchMock)); 1165 | 1166 | expect(url.searchParams.get('environment')).toEqual('default'); 1167 | }); 1168 | 1169 | test('Should setContextField with userId', async () => { 1170 | const userId = 'some-id-123'; 1171 | const config: IConfig = { 1172 | url: 'http://localhost/test', 1173 | clientKey: '12', 1174 | appName: 'web', 1175 | }; 1176 | const client = new UnleashClient(config); 1177 | client.setContextField('userId', userId); 1178 | const context = client.getContext(); 1179 | expect(context.userId).toBe(userId); 1180 | }); 1181 | 1182 | test('Should removeContextField', async () => { 1183 | const userId = 'some-id-123'; 1184 | const customValue = 'customValue'; 1185 | const config: IConfig = { 1186 | url: 'http://localhost/test', 1187 | clientKey: '12', 1188 | appName: 'web', 1189 | }; 1190 | const client = new UnleashClient(config); 1191 | client.setContextField('userId', userId); 1192 | client.setContextField('customField', customValue); 1193 | 1194 | client.removeContextField('userId'); 1195 | client.removeContextField('customField'); 1196 | const context = client.getContext(); 1197 | 1198 | expect(context).toEqual({ 1199 | appName: 'web', 1200 | environment: 'default', 1201 | properties: {}, 1202 | }); 1203 | }); 1204 | 1205 | test('Should setContextField with sessionId', async () => { 1206 | const sessionId = 'some-session-id-123'; 1207 | const config: IConfig = { 1208 | url: 'http://localhost/test', 1209 | clientKey: '12', 1210 | appName: 'web', 1211 | }; 1212 | const client = new UnleashClient(config); 1213 | client.setContextField('sessionId', sessionId); 1214 | const context = client.getContext(); 1215 | expect(context.sessionId).toBe(sessionId); 1216 | }); 1217 | 1218 | test('Should setContextField with remoteAddress', async () => { 1219 | const remoteAddress = '10.0.0.1'; 1220 | const config: IConfig = { 1221 | url: 'http://localhost/test', 1222 | clientKey: '12', 1223 | appName: 'web', 1224 | }; 1225 | const client = new UnleashClient(config); 1226 | client.setContextField('remoteAddress', remoteAddress); 1227 | const context = client.getContext(); 1228 | expect(context.remoteAddress).toBe(remoteAddress); 1229 | }); 1230 | 1231 | test('Should setContextField with currentTime', async () => { 1232 | const currentTime = '2022-01-22T13:00:00.000Z'; 1233 | const config: IConfig = { 1234 | url: 'http://localhost/test', 1235 | clientKey: '12', 1236 | appName: 'web', 1237 | }; 1238 | const client = new UnleashClient(config); 1239 | client.setContextField('currentTime', currentTime); 1240 | const context = client.getContext(); 1241 | expect(context.currentTime).toBe(currentTime); 1242 | }); 1243 | 1244 | test('Should setContextField with custom property', async () => { 1245 | const clientId = 'some-client-id-443'; 1246 | const config: IConfig = { 1247 | url: 'http://localhost/test', 1248 | clientKey: '12', 1249 | appName: 'web', 1250 | }; 1251 | const client = new UnleashClient(config); 1252 | client.setContextField('clientId', clientId); 1253 | const context = client.getContext(); 1254 | expect(context.properties?.clientId).toBe(clientId); 1255 | }); 1256 | 1257 | test('Should setContextField with custom property and keep existing props', async () => { 1258 | const clientId = 'some-client-id-443'; 1259 | const initialContext = { properties: { someField: '123' } }; 1260 | const config: IConfig = { 1261 | url: 'http://localhost/test', 1262 | clientKey: '12', 1263 | appName: 'web', 1264 | context: initialContext, 1265 | }; 1266 | const client = new UnleashClient(config); 1267 | client.setContextField('clientId', clientId); 1268 | const context = client.getContext(); 1269 | expect(context.properties?.clientId).toBe(clientId); 1270 | expect(context.properties?.someField).toBe( 1271 | initialContext.properties.someField 1272 | ); 1273 | }); 1274 | 1275 | test('Should override userId via setContextField', async () => { 1276 | const userId = 'some-user-id-552'; 1277 | const config: IConfig = { 1278 | url: 'http://localhost/test', 1279 | clientKey: '12', 1280 | appName: 'web', 1281 | context: { userId: 'old' }, 1282 | }; 1283 | const client = new UnleashClient(config); 1284 | client.setContextField('userId', userId); 1285 | const context = client.getContext(); 1286 | expect(context.userId).toBe(userId); 1287 | }); 1288 | 1289 | test('Initializing client twice should show a console warning', async () => { 1290 | console.error = jest.fn(); 1291 | const config: IConfig = { 1292 | url: 'http://localhost/test', 1293 | clientKey: '12', 1294 | appName: 'web', 1295 | context: { userId: 'old' }, 1296 | }; 1297 | const client = new UnleashClient(config); 1298 | 1299 | await client.start(); 1300 | await client.start(); 1301 | // Expect console.error to be called once before start runs. 1302 | expect(console.error).toHaveBeenCalledTimes(2); 1303 | }); 1304 | 1305 | test('Should pass under custom header clientKey', async () => { 1306 | fetchMock.mockResponseOnce(JSON.stringify(data)); 1307 | 1308 | const config: IConfig = { 1309 | url: 'http://localhost/test', 1310 | clientKey: '12', 1311 | appName: 'web', 1312 | headerName: 'NotAuthorization', 1313 | }; 1314 | const client = new UnleashClient(config); 1315 | 1316 | client.on(EVENTS.UPDATE, () => { 1317 | const request = getTypeSafeRequest(fetchMock, 0); 1318 | 1319 | expect(fetchMock.mock.calls.length).toEqual(1); 1320 | expect(request.headers).toMatchObject({ 1321 | NotAuthorization: '12', 1322 | }); 1323 | client.stop(); 1324 | }); 1325 | 1326 | await client.start(); 1327 | 1328 | jest.advanceTimersByTime(999); 1329 | }); 1330 | 1331 | test('Should emit impression events on isEnabled calls when impressionData is true', (done) => { 1332 | const bootstrap = [ 1333 | { 1334 | name: 'impression', 1335 | enabled: true, 1336 | variant: { 1337 | name: 'disabled', 1338 | enabled: false, 1339 | feature_enabled: true, 1340 | }, 1341 | impressionData: true, 1342 | }, 1343 | ]; 1344 | 1345 | const config: IConfig = { 1346 | url: 'http://localhost/test', 1347 | clientKey: '12', 1348 | appName: 'web', 1349 | bootstrap, 1350 | }; 1351 | const client = new UnleashClient(config); 1352 | client.start(); 1353 | 1354 | client.on(EVENTS.READY, () => { 1355 | const isEnabled = client.isEnabled('impression'); 1356 | expect(isEnabled).toBe(true); 1357 | }); 1358 | 1359 | client.on(EVENTS.IMPRESSION, (event: any) => { 1360 | expect(event.featureName).toBe('impression'); 1361 | expect(event.eventType).toBe('isEnabled'); 1362 | client.stop(); 1363 | done(); 1364 | }); 1365 | }); 1366 | 1367 | test('Should pass custom headers', async () => { 1368 | fetchMock.mockResponses( 1369 | [JSON.stringify(data), { status: 200 }], 1370 | [JSON.stringify(data), { status: 200 }] 1371 | ); 1372 | const config: IConfig = { 1373 | url: 'http://localhost/test', 1374 | clientKey: 'extrakey', 1375 | appName: 'web', 1376 | customHeaders: { 1377 | customheader1: 'header1val', 1378 | customheader2: 'header2val', 1379 | }, 1380 | }; 1381 | const client = new UnleashClient(config); 1382 | await client.start(); 1383 | 1384 | jest.advanceTimersByTime(1001); 1385 | 1386 | const featureRequest = getTypeSafeRequest(fetchMock, 0); 1387 | 1388 | expect(featureRequest.headers).toMatchObject({ 1389 | customheader1: 'header1val', 1390 | customheader2: 'header2val', 1391 | }); 1392 | 1393 | client.isEnabled('count-metrics'); 1394 | jest.advanceTimersByTime(2001); 1395 | 1396 | const metricsRequest = getTypeSafeRequest(fetchMock, 1); 1397 | 1398 | expect(metricsRequest.headers).toMatchObject({ 1399 | customheader1: 'header1val', 1400 | customheader2: 'header2val', 1401 | }); 1402 | }); 1403 | 1404 | test('Should add unleash identification headers', async () => { 1405 | fetchMock.mockResponses( 1406 | [JSON.stringify(data), { status: 200 }], 1407 | [JSON.stringify(data), { status: 200 }] 1408 | ); 1409 | const appName = 'unleash-client-test'; 1410 | const config: IConfig = { 1411 | url: 'http://localhost/test', 1412 | clientKey: 'some123key', 1413 | appName, 1414 | }; 1415 | const client = new UnleashClient(config); 1416 | await client.start(); 1417 | 1418 | const featureRequest = getTypeSafeRequest(fetchMock, 0); 1419 | 1420 | client.isEnabled('count-metrics'); 1421 | jest.advanceTimersByTime(2001); 1422 | 1423 | const metricsRequest = getTypeSafeRequest(fetchMock, 1); 1424 | 1425 | const uuidFormat = 1426 | /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; 1427 | 1428 | const expectedHeaders = { 1429 | // will be replaced at build time with the actual version 1430 | 'unleash-sdk': 'unleash-client-js:__VERSION__', 1431 | 'unleash-connection-id': expect.stringMatching(uuidFormat), 1432 | 'unleash-appname': appName, 1433 | }; 1434 | 1435 | const getConnectionId = (request: any) => 1436 | request.headers['unleash-connection-id']; 1437 | 1438 | expect(featureRequest.headers).toMatchObject(expectedHeaders); 1439 | expect(metricsRequest.headers).toMatchObject(expectedHeaders); 1440 | expect(getConnectionId(featureRequest)).toEqual( 1441 | getConnectionId(metricsRequest) 1442 | ); 1443 | }); 1444 | 1445 | test('Should emit impression events on getVariant calls when impressionData is true', (done) => { 1446 | const bootstrap = [ 1447 | { 1448 | name: 'impression-variant', 1449 | enabled: true, 1450 | variant: { 1451 | name: 'disabled', 1452 | enabled: false, 1453 | feature_enabled: true, 1454 | }, 1455 | impressionData: true, 1456 | }, 1457 | ]; 1458 | 1459 | const config: IConfig = { 1460 | url: 'http://localhost/test', 1461 | clientKey: '12', 1462 | appName: 'web', 1463 | bootstrap, 1464 | }; 1465 | const client = new UnleashClient(config); 1466 | client.start(); 1467 | 1468 | client.on(EVENTS.READY, () => { 1469 | const isEnabled = client.getVariant('impression-variant'); 1470 | expect(isEnabled).toBe(true); 1471 | }); 1472 | 1473 | client.on(EVENTS.IMPRESSION, (event: any) => { 1474 | expect(event.featureName).toBe('impression-variant'); 1475 | expect(event.eventType).toBe('getVariant'); 1476 | expect(event.impressionData).toBe(true); 1477 | client.stop(); 1478 | done(); 1479 | }); 1480 | }); 1481 | 1482 | test('Should not emit impression events on isEnabled calls when impressionData is false', (done) => { 1483 | const bootstrap = [ 1484 | { 1485 | name: 'impression', 1486 | enabled: true, 1487 | variant: { 1488 | name: 'disabled', 1489 | enabled: false, 1490 | feature_enabled: true, 1491 | }, 1492 | impressionData: false, 1493 | }, 1494 | ]; 1495 | 1496 | const config: IConfig = { 1497 | url: 'http://localhost/test', 1498 | clientKey: '12', 1499 | appName: 'web', 1500 | bootstrap, 1501 | }; 1502 | const client = new UnleashClient(config); 1503 | client.start(); 1504 | 1505 | client.on(EVENTS.READY, () => { 1506 | const isEnabled = client.isEnabled('impression'); 1507 | expect(isEnabled).toBe(true); 1508 | client.stop(); 1509 | done(); 1510 | }); 1511 | 1512 | client.on(EVENTS.IMPRESSION, () => { 1513 | client.stop(); 1514 | fail('SDK should not emit impression event'); 1515 | }); 1516 | }); 1517 | 1518 | test('Should emit impression events on isEnabled calls when impressionData is false and impressionDataAll is true', (done) => { 1519 | const bootstrap = [ 1520 | { 1521 | name: 'impression', 1522 | enabled: true, 1523 | variant: { 1524 | name: 'disabled', 1525 | enabled: false, 1526 | feature_enabled: true, 1527 | }, 1528 | impressionData: false, 1529 | }, 1530 | ]; 1531 | 1532 | const config: IConfig = { 1533 | url: 'http://localhost/test', 1534 | clientKey: '12', 1535 | appName: 'web', 1536 | bootstrap, 1537 | impressionDataAll: true, 1538 | }; 1539 | const client = new UnleashClient(config); 1540 | client.start(); 1541 | 1542 | client.on(EVENTS.READY, () => { 1543 | const isEnabled = client.isEnabled('impression'); 1544 | expect(isEnabled).toBe(true); 1545 | }); 1546 | 1547 | client.on(EVENTS.IMPRESSION, (event: any) => { 1548 | try { 1549 | expect(event.featureName).toBe('impression'); 1550 | expect(event.eventType).toBe('isEnabled'); 1551 | expect(event.impressionData).toBe(false); 1552 | client.stop(); 1553 | done(); 1554 | } catch (e) { 1555 | client.stop(); 1556 | done(e); 1557 | } 1558 | }); 1559 | }); 1560 | 1561 | test('Should emit impression events on isEnabled calls when toggle is unknown and impressionDataAll is true', (done) => { 1562 | const bootstrap = [ 1563 | { 1564 | name: 'impression', 1565 | enabled: true, 1566 | variant: { 1567 | name: 'disabled', 1568 | enabled: false, 1569 | feature_enabled: true, 1570 | }, 1571 | impressionData: false, 1572 | }, 1573 | ]; 1574 | 1575 | const config: IConfig = { 1576 | url: 'http://localhost/test', 1577 | clientKey: '12', 1578 | appName: 'web', 1579 | bootstrap, 1580 | impressionDataAll: true, 1581 | }; 1582 | const client = new UnleashClient(config); 1583 | client.start(); 1584 | 1585 | client.on(EVENTS.READY, () => { 1586 | const isEnabled = client.isEnabled('unknown'); 1587 | expect(isEnabled).toBe(true); 1588 | }); 1589 | 1590 | client.on(EVENTS.IMPRESSION, (event: any) => { 1591 | expect(event.featureName).toBe('unknown'); 1592 | expect(event.eventType).toBe('isEnabled'); 1593 | expect(event.enabled).toBe(false); 1594 | expect(event.impressionData).toBe(undefined); 1595 | client.stop(); 1596 | done(); 1597 | }); 1598 | }); 1599 | 1600 | test('Should emit impression events on getVariant calls when impressionData is false and impressionDataAll is true', (done) => { 1601 | const bootstrap = [ 1602 | { 1603 | name: 'impression-variant', 1604 | enabled: true, 1605 | variant: { 1606 | name: 'disabled', 1607 | enabled: false, 1608 | feature_enabled: true, 1609 | }, 1610 | impressionData: false, 1611 | }, 1612 | ]; 1613 | 1614 | const config: IConfig = { 1615 | url: 'http://localhost/test', 1616 | clientKey: '12', 1617 | appName: 'web', 1618 | bootstrap, 1619 | impressionDataAll: true, 1620 | }; 1621 | const client = new UnleashClient(config); 1622 | client.start(); 1623 | 1624 | client.on(EVENTS.READY, () => { 1625 | const isEnabled = client.getVariant('impression-variant'); 1626 | expect(isEnabled).toBe(true); 1627 | }); 1628 | 1629 | client.on(EVENTS.IMPRESSION, (event: any) => { 1630 | try { 1631 | expect(event.featureName).toBe('impression-variant'); 1632 | expect(event.eventType).toBe('getVariant'); 1633 | expect(event.impressionData).toBe(false); 1634 | client.stop(); 1635 | done(); 1636 | } catch (e) { 1637 | client.stop(); 1638 | done(e); 1639 | } 1640 | }); 1641 | }); 1642 | 1643 | test('Should publish ready only when the first fetch was successful', async () => { 1644 | fetchMock.mockResponse(JSON.stringify(data)); 1645 | const config: IConfig = { 1646 | url: 'http://localhost/test', 1647 | clientKey: '12', 1648 | appName: 'web', 1649 | refreshInterval: 1, 1650 | }; 1651 | const client = new UnleashClient(config); 1652 | await client.start(); 1653 | 1654 | let readyCount = 0; 1655 | 1656 | client.on(EVENTS.READY, () => { 1657 | const isEnabled = client.isEnabled('simpleToggle'); 1658 | expect(isEnabled).toBe(true); 1659 | readyCount++; 1660 | client.stop(); 1661 | expect(readyCount).toEqual(1); 1662 | }); 1663 | 1664 | jest.advanceTimersByTime(1001); 1665 | jest.advanceTimersByTime(1001); 1666 | 1667 | expect(fetchMock).toHaveBeenCalledTimes(3); 1668 | }); 1669 | 1670 | test('Should be able to configure UnleashClient with a URL instance', () => { 1671 | const url = new URL('test', 'http://localhost'); 1672 | const config: IConfig = { 1673 | url, 1674 | clientKey: '12', 1675 | appName: 'web', 1676 | }; 1677 | const client = new UnleashClient(config); 1678 | expect(client).toHaveProperty('url', url); 1679 | }); 1680 | 1681 | test("Should update toggles even when refresh interval is set to '0'", async () => { 1682 | fetchMock.mockResponse(JSON.stringify(data)); 1683 | const config: IConfig = { 1684 | url: 'http://localhost/test', 1685 | clientKey: '12', 1686 | appName: 'web', 1687 | refreshInterval: 0, 1688 | }; 1689 | const client = new UnleashClient(config); 1690 | await client.start(); 1691 | expect(fetchMock).toHaveBeenCalledTimes(1); 1692 | 1693 | await client.updateContext({ userId: '123' }); 1694 | expect(fetchMock).toHaveBeenCalledTimes(2); 1695 | }); 1696 | 1697 | test.each([null, undefined])( 1698 | 'Setting a context field to %s should clear it from the context', 1699 | async () => { 1700 | fetchMock.mockResponse(JSON.stringify(data)); 1701 | const config: IConfig = { 1702 | url: 'http://localhost/test', 1703 | clientKey: '12', 1704 | appName: 'web', 1705 | }; 1706 | const client = new UnleashClient(config); 1707 | await client.start(); 1708 | 1709 | await client.updateContext({ userId: '123' }); 1710 | expect(client.getContext().userId).toEqual('123'); 1711 | 1712 | const userId = undefined; 1713 | await client.updateContext({ userId }); 1714 | 1715 | expect(client.getContext().userId).toBeUndefined(); 1716 | } 1717 | ); 1718 | 1719 | test('Should report metrics', async () => { 1720 | const toggles: IToggle[] = [ 1721 | { 1722 | name: 'toggle', 1723 | enabled: true, 1724 | variant: { 1725 | name: 'variant', 1726 | enabled: true, 1727 | feature_enabled: true, 1728 | }, 1729 | impressionData: true, 1730 | }, 1731 | ]; 1732 | 1733 | const config: IConfig = { 1734 | url: 'http://localhost/test', 1735 | clientKey: '12', 1736 | appName: 'web', 1737 | fetch: async () => { 1738 | return { 1739 | ok: true, 1740 | headers: new Map(), 1741 | async json() { 1742 | return { toggles }; 1743 | }, 1744 | }; 1745 | }, 1746 | }; 1747 | const client = new UnleashClient(config); 1748 | await client.start(); 1749 | 1750 | client.getVariant('toggle'); 1751 | client.getVariant('non-existent-toggle'); 1752 | jest.advanceTimersByTime(2500); // fist metric sent after 2 seconds 1753 | 1754 | const data = await new Promise((resolve) => { 1755 | client.on(EVENTS.SENT, (data: any) => { 1756 | resolve(data); 1757 | }); 1758 | }); 1759 | expect(data).toMatchObject({ 1760 | appName: 'web', 1761 | bucket: { 1762 | toggles: { 1763 | 'non-existent-toggle': { 1764 | yes: 0, 1765 | no: 1, 1766 | variants: { disabled: 1 }, 1767 | }, 1768 | toggle: { yes: 1, no: 0, variants: { variant: 1 } }, 1769 | }, 1770 | }, 1771 | }); 1772 | client.stop(); 1773 | }); 1774 | 1775 | test('should send metrics when sendMetrics called', async () => { 1776 | const config: IConfig = { 1777 | url: 'http://localhost/test', 1778 | clientKey: '12', 1779 | appName: 'web', 1780 | }; 1781 | 1782 | jest.spyOn(Metrics.prototype, 'sendMetrics'); 1783 | 1784 | const client = new UnleashClient(config); 1785 | 1786 | client.start(); 1787 | 1788 | expect(Metrics.prototype.sendMetrics).not.toHaveBeenCalled(); 1789 | 1790 | await client.sendMetrics(); 1791 | 1792 | expect(Metrics.prototype.sendMetrics).toHaveBeenCalled(); 1793 | }); 1794 | 1795 | test('Should emit RECOVERED event when sdkStatus is error and status is less than 400', (done) => { 1796 | const data = { status: 200 }; // replace with the actual data you want to test 1797 | fetchMock.mockResponseOnce(JSON.stringify(data), { status: 200 }); 1798 | 1799 | const config: IConfig = { 1800 | url: 'http://localhost/test', 1801 | clientKey: '12', 1802 | appName: 'web', 1803 | }; 1804 | 1805 | const client = new UnleashClient(config); 1806 | 1807 | client.start(); 1808 | 1809 | client.on(EVENTS.INIT, () => { 1810 | // Set error after the SDK has moved through the sdk states internally 1811 | // eslint-disable-next-line 1812 | // @ts-ignore - Private method by design, but we want to access it in tests 1813 | client.sdkState = 'error'; 1814 | }); 1815 | 1816 | client.on(EVENTS.RECOVERED, () => { 1817 | // eslint-disable-next-line 1818 | // @ts-ignore - Private method by design. but we want to access it in tests 1819 | expect(client.sdkState).toBe('healthy'); 1820 | client.stop(); 1821 | done(); 1822 | }); 1823 | }); 1824 | 1825 | test('Should set sdkState to healthy when client is started', (done) => { 1826 | const config: IConfig = { 1827 | url: 'http://localhost/test', 1828 | clientKey: '12', 1829 | appName: 'web', 1830 | }; 1831 | 1832 | const client = new UnleashClient(config); 1833 | // eslint-disable-next-line 1834 | // @ts-ignore - Private method by design, but we want to access it in tests 1835 | expect(client.sdkState).toBe('initializing'); 1836 | 1837 | client.start(); 1838 | 1839 | client.on(EVENTS.INIT, () => { 1840 | // eslint-disable-next-line 1841 | // @ts-ignore - Private method by design, but we want to access it in tests 1842 | expect(client.sdkState).toBe('healthy'); 1843 | client.stop(); 1844 | done(); 1845 | }); 1846 | }); 1847 | 1848 | describe('READY event emission', () => { 1849 | let client: UnleashClient; 1850 | 1851 | const config: IConfig = { 1852 | url: 'http://localhost/test', 1853 | clientKey: '12', 1854 | appName: 'web', 1855 | bootstrap: [ 1856 | { 1857 | enabled: false, 1858 | name: 'test-frontend', 1859 | variant: { name: 'some-variant', enabled: false }, 1860 | impressionData: false, 1861 | }, 1862 | ], 1863 | bootstrapOverride: false, 1864 | fetch: async () => { 1865 | return { 1866 | ok: true, 1867 | headers: new Map(), 1868 | async json() { 1869 | return {}; 1870 | }, 1871 | }; 1872 | }, 1873 | }; 1874 | 1875 | beforeEach(() => { 1876 | fetchMock.resetMocks(); 1877 | client = new UnleashClient(config); 1878 | jest.spyOn(client, 'emit'); 1879 | }); 1880 | 1881 | test('should emit READY when response is OK and not 304, and conditions are met', async () => { 1882 | // Mock a successful fetch response that is not 304 1883 | fetchMock.mockResponseOnce( 1884 | JSON.stringify({ 1885 | toggles: [{ feature: 'test-feature', enabled: true }], 1886 | }), 1887 | { 1888 | status: 200, 1889 | headers: { ETag: 'new-etag' }, 1890 | } 1891 | ); 1892 | 1893 | expect(client.emit).toHaveBeenCalledWith(EVENTS.READY); 1894 | }); 1895 | }); 1896 | 1897 | test('should be in ready state if bootstrapping', (done) => { 1898 | const config: IConfig = { 1899 | url: 'http://localhost/test', 1900 | clientKey: '12', 1901 | appName: 'web', 1902 | bootstrap: [ 1903 | { 1904 | enabled: false, 1905 | name: 'test-frontend', 1906 | variant: { name: 'some-variant', enabled: false }, 1907 | impressionData: false, 1908 | }, 1909 | ], 1910 | fetch: async () => {}, 1911 | }; 1912 | 1913 | const client = new UnleashClient(config); 1914 | 1915 | client.on(EVENTS.READY, () => { 1916 | expect(client.isReady()).toBe(true); 1917 | client.stop(); 1918 | done(); 1919 | }); 1920 | }); 1921 | 1922 | describe('Experimental options togglesStorageTTL disabled', () => { 1923 | let storageProvider: IStorageProvider; 1924 | let saveSpy: jest.SpyInstance; 1925 | 1926 | class Store implements IStorageProvider { 1927 | public async save() { 1928 | return Promise.resolve(); 1929 | } 1930 | 1931 | public async get() { 1932 | return Promise.resolve([]); 1933 | } 1934 | } 1935 | 1936 | beforeEach(() => { 1937 | storageProvider = new Store(); 1938 | saveSpy = jest.spyOn(storageProvider, 'save'); 1939 | jest.clearAllMocks(); 1940 | }); 1941 | 1942 | test('Should not store last update flag when fetch is successful', async () => { 1943 | fetchMock.mockResponseOnce(JSON.stringify(data)); 1944 | 1945 | const config: IConfig = { 1946 | url: 'http://localhost/test', 1947 | clientKey: '12', 1948 | appName: 'web', 1949 | storageProvider, 1950 | experimental: {}, 1951 | }; 1952 | 1953 | const client = new UnleashClient(config); 1954 | await client.start(); 1955 | expect(fetchMock).toHaveBeenCalledTimes(1); 1956 | expect(saveSpy).not.toHaveBeenCalledWith( 1957 | lastUpdateKey, 1958 | expect.anything() 1959 | ); 1960 | }); 1961 | 1962 | test('Should not store last update flag even when bootstrap is set', async () => { 1963 | localStorage.clear(); 1964 | const bootstrap = [ 1965 | { 1966 | name: 'toggles', 1967 | enabled: true, 1968 | variant: { 1969 | name: 'disabled', 1970 | enabled: false, 1971 | feature_enabled: true, 1972 | }, 1973 | impressionData: true, 1974 | }, 1975 | ]; 1976 | 1977 | const config: IConfig = { 1978 | url: 'http://localhost/test', 1979 | clientKey: '12', 1980 | appName: 'web', 1981 | bootstrap, 1982 | storageProvider, 1983 | }; 1984 | const client = new UnleashClient(config); 1985 | await client.start(); 1986 | expect(saveSpy).not.toHaveBeenCalledWith( 1987 | lastUpdateKey, 1988 | expect.anything() 1989 | ); 1990 | }); 1991 | }); 1992 | 1993 | describe('Experimental options togglesStorageTTL enabled', () => { 1994 | let storage: IStorageProvider; 1995 | let fakeNow: number; 1996 | 1997 | describe('Handling last update flag storage', () => { 1998 | let storageProvider: IStorageProvider; 1999 | let saveSpy: jest.SpyInstance; 2000 | 2001 | class Store implements IStorageProvider { 2002 | public async save() { 2003 | return Promise.resolve(); 2004 | } 2005 | 2006 | public async get() { 2007 | return Promise.resolve([]); 2008 | } 2009 | } 2010 | 2011 | beforeEach(() => { 2012 | storageProvider = new Store(); 2013 | saveSpy = jest.spyOn(storageProvider, 'save'); 2014 | jest.clearAllMocks(); 2015 | }); 2016 | 2017 | test('Should store last update flag when fetch is successful', async () => { 2018 | const startTime = Date.now(); 2019 | fetchMock.mockResponseOnce(JSON.stringify(data)); 2020 | 2021 | const config: IConfig = { 2022 | url: 'http://localhost/test', 2023 | clientKey: '12', 2024 | appName: 'web', 2025 | storageProvider, 2026 | experimental: { 2027 | togglesStorageTTL: 60, 2028 | }, 2029 | }; 2030 | 2031 | const client = new UnleashClient(config); 2032 | await client.start(); 2033 | expect(saveSpy).toHaveBeenCalledWith(lastUpdateKey, { 2034 | key: expect.any(String), 2035 | timestamp: expect.any(Number), 2036 | }); 2037 | expect( 2038 | saveSpy.mock.lastCall?.at(1).timestamp 2039 | ).toBeGreaterThanOrEqual(startTime); 2040 | }); 2041 | 2042 | test('Should store last update flag when fetch is successful with 304 status', async () => { 2043 | const startTime = Date.now(); 2044 | fetchMock.mockResponseOnce(JSON.stringify(data), { status: 304 }); 2045 | 2046 | const config: IConfig = { 2047 | url: 'http://localhost/test', 2048 | clientKey: '12', 2049 | appName: 'web', 2050 | storageProvider, 2051 | experimental: { 2052 | togglesStorageTTL: 60, 2053 | }, 2054 | }; 2055 | 2056 | const client = new UnleashClient(config); 2057 | await client.start(); 2058 | expect(saveSpy).toHaveBeenCalledWith(lastUpdateKey, { 2059 | key: expect.any(String), 2060 | timestamp: expect.any(Number), 2061 | }); 2062 | expect( 2063 | saveSpy.mock.lastCall?.at(1).timestamp 2064 | ).toBeGreaterThanOrEqual(startTime); 2065 | }); 2066 | 2067 | test('Should not store last update flag when fetch is not successful', async () => { 2068 | fetchMock.mockResponseOnce('', { status: 500 }); 2069 | 2070 | const config: IConfig = { 2071 | url: 'http://localhost/test', 2072 | clientKey: '12', 2073 | appName: 'web', 2074 | storageProvider, 2075 | experimental: { 2076 | togglesStorageTTL: 60, 2077 | }, 2078 | }; 2079 | 2080 | const client = new UnleashClient(config); 2081 | await client.start(); 2082 | expect(saveSpy).not.toHaveBeenCalledWith( 2083 | lastUpdateKey, 2084 | expect.any(Number) 2085 | ); 2086 | }); 2087 | }); 2088 | 2089 | describe('Handling last update flag storage hash value', () => { 2090 | let storageProvider: IStorageProvider; 2091 | let saveSpy: jest.SpyInstance; 2092 | 2093 | class Store implements IStorageProvider { 2094 | public async save() { 2095 | return Promise.resolve(); 2096 | } 2097 | 2098 | public async get() { 2099 | return Promise.resolve([]); 2100 | } 2101 | } 2102 | 2103 | beforeEach(() => { 2104 | storageProvider = new Store(); 2105 | saveSpy = jest.spyOn(storageProvider, 'save'); 2106 | jest.clearAllMocks(); 2107 | }); 2108 | 2109 | test('Hash value computed should not change when the context value not change', async () => { 2110 | fetchMock.mockResponse(JSON.stringify({})); 2111 | 2112 | const config: IConfig = { 2113 | url: 'http://localhost/test', 2114 | clientKey: '12', 2115 | appName: 'web', 2116 | storageProvider, 2117 | experimental: { 2118 | togglesStorageTTL: 60, 2119 | }, 2120 | }; 2121 | const client = new UnleashClient(config); 2122 | await client.start(); 2123 | 2124 | const firstHash = saveSpy.mock.lastCall?.at(1).key; 2125 | await client.updateContext({}); 2126 | 2127 | const secondHash = saveSpy.mock.lastCall?.at(1).key; 2128 | 2129 | expect(firstHash).not.toBeUndefined(); 2130 | expect(secondHash).not.toBeUndefined(); 2131 | expect(firstHash).toEqual(secondHash); 2132 | }); 2133 | 2134 | test('Hash value computed should change when context value change', async () => { 2135 | fetchMock.mockResponse(JSON.stringify({})); 2136 | 2137 | const config: IConfig = { 2138 | url: 'http://localhost/test', 2139 | clientKey: '12', 2140 | appName: 'web', 2141 | storageProvider, 2142 | experimental: { 2143 | togglesStorageTTL: 60, 2144 | }, 2145 | }; 2146 | const client = new UnleashClient(config); 2147 | await client.start(); 2148 | 2149 | const firstHash = saveSpy.mock.lastCall?.at(1).key; 2150 | 2151 | await client.updateContext({ userId: '123' }); 2152 | 2153 | const secondHash = saveSpy.mock.lastCall?.at(1).key; 2154 | 2155 | expect(firstHash).not.toBeUndefined(); 2156 | expect(secondHash).not.toBeUndefined(); 2157 | expect(firstHash).not.toEqual(secondHash); 2158 | }); 2159 | }); 2160 | 2161 | describe('During bootstrap initialisation', () => { 2162 | beforeEach(async () => { 2163 | storage = new InMemoryStorageProvider(); 2164 | jest.clearAllMocks(); 2165 | }); 2166 | 2167 | afterEach(() => { 2168 | jest.useRealTimers(); 2169 | }); 2170 | 2171 | test('Should store last update flag when bootstrap is set', async () => { 2172 | expect.assertions(1); 2173 | const bootstrap = [ 2174 | { 2175 | name: 'toggles', 2176 | enabled: true, 2177 | variant: { 2178 | name: 'disabled', 2179 | enabled: false, 2180 | feature_enabled: true, 2181 | }, 2182 | impressionData: true, 2183 | }, 2184 | ]; 2185 | 2186 | const config: IConfig = { 2187 | url: 'http://localhost/test', 2188 | clientKey: '12', 2189 | appName: 'web', 2190 | bootstrap, 2191 | storageProvider: storage, 2192 | experimental: { 2193 | togglesStorageTTL: 60, 2194 | }, 2195 | }; 2196 | const client = new UnleashClient(config); 2197 | 2198 | client.on(EVENTS.READY, async () => { 2199 | expect(await storage.get(lastUpdateKey)).not.toBeUndefined(); 2200 | }); 2201 | }); 2202 | 2203 | test('Should not store last update flag when bootstrap is not set', async () => { 2204 | expect.assertions(1); 2205 | const config: IConfig = { 2206 | url: 'http://localhost/test', 2207 | clientKey: '12', 2208 | appName: 'web', 2209 | storageProvider: storage, 2210 | experimental: { 2211 | togglesStorageTTL: 60, 2212 | }, 2213 | }; 2214 | const client = new UnleashClient(config); 2215 | client.on(EVENTS.INIT, async () => { 2216 | expect(await storage.get(lastUpdateKey)).toBeUndefined(); 2217 | }); 2218 | }); 2219 | }); 2220 | 2221 | describe('With a previous storage initialisation', () => { 2222 | beforeEach(async () => { 2223 | fakeNow = new Date('2024-01-01').getTime(); 2224 | jest.useFakeTimers(); 2225 | jest.setSystemTime(fakeNow); 2226 | storage = new InMemoryStorageProvider(); 2227 | 2228 | fetchMock.mockResponseOnce(JSON.stringify(data)).mockResponseOnce( 2229 | JSON.stringify({ 2230 | toggles: [ 2231 | { 2232 | name: 'simpleToggle', 2233 | enabled: false, 2234 | impressionData: true, 2235 | }, 2236 | ], 2237 | }) 2238 | ); 2239 | 2240 | const config: IConfig = { 2241 | url: 'http://localhost/test', 2242 | clientKey: '12', 2243 | appName: 'web', 2244 | storageProvider: storage, 2245 | experimental: { 2246 | togglesStorageTTL: 60, 2247 | }, 2248 | }; 2249 | // performing an initial fetch to populate the toggles and lastUpdate timestamp 2250 | const client = new UnleashClient(config); 2251 | await client.start(); 2252 | client.stop(); 2253 | 2254 | expect(fetchMock).toHaveBeenCalledTimes(1); 2255 | fetchMock.mockClear(); 2256 | }); 2257 | 2258 | afterEach(() => { 2259 | jest.useRealTimers(); 2260 | }); 2261 | 2262 | test('Should not perform an initial fetch when toggles are up to date', async () => { 2263 | jest.setSystemTime(fakeNow + 59000); 2264 | const config: IConfig = { 2265 | url: 'http://localhost/test', 2266 | clientKey: '12', 2267 | appName: 'web', 2268 | storageProvider: storage, 2269 | experimental: { 2270 | togglesStorageTTL: 60, 2271 | }, 2272 | }; 2273 | const client = new UnleashClient(config); 2274 | await client.start(); 2275 | const isEnabled = client.isEnabled('simpleToggle'); 2276 | expect(isEnabled).toBe(true); 2277 | client.stop(); 2278 | expect(fetchMock).toHaveBeenCalledTimes(0); 2279 | }); 2280 | 2281 | test('Should perform an initial fetch when toggles are expired', async () => { 2282 | jest.setSystemTime(fakeNow + 61000); 2283 | 2284 | const config: IConfig = { 2285 | url: 'http://localhost/test', 2286 | clientKey: '12', 2287 | appName: 'web', 2288 | storageProvider: storage, 2289 | experimental: { 2290 | togglesStorageTTL: 60, 2291 | }, 2292 | }; 2293 | const client = new UnleashClient(config); 2294 | await client.start(); 2295 | const isEnabled = client.isEnabled('simpleToggle'); 2296 | expect(isEnabled).toBe(false); 2297 | client.stop(); 2298 | expect(fetchMock).toHaveBeenCalledTimes(1); 2299 | }); 2300 | 2301 | test('Should perform an initial fetch when system time goes back into the past', async () => { 2302 | jest.setSystemTime(fakeNow - 1000); 2303 | 2304 | const config: IConfig = { 2305 | url: 'http://localhost/test', 2306 | clientKey: '12', 2307 | appName: 'web', 2308 | storageProvider: storage, 2309 | experimental: { 2310 | togglesStorageTTL: 60, 2311 | }, 2312 | }; 2313 | const client = new UnleashClient(config); 2314 | await client.start(); 2315 | const isEnabled = client.isEnabled('simpleToggle'); 2316 | expect(isEnabled).toBe(false); 2317 | client.stop(); 2318 | expect(fetchMock).toHaveBeenCalledTimes(1); 2319 | }); 2320 | 2321 | test('Should perform an initial fetch when context has changed, even if flags are up to date', async () => { 2322 | jest.setSystemTime(fakeNow + 59000); 2323 | const config: IConfig = { 2324 | url: 'http://localhost/test', 2325 | clientKey: '12', 2326 | appName: 'web', 2327 | storageProvider: storage, 2328 | experimental: { 2329 | togglesStorageTTL: 60, 2330 | }, 2331 | context: { 2332 | properties: { 2333 | newProperty: 'newProperty', 2334 | }, 2335 | }, 2336 | }; 2337 | const client = new UnleashClient(config); 2338 | await client.start(); 2339 | const isEnabled = client.isEnabled('simpleToggle'); 2340 | expect(isEnabled).toBe(false); 2341 | client.stop(); 2342 | expect(fetchMock).toHaveBeenCalledTimes(1); 2343 | }); 2344 | 2345 | test('Should send ready event when toggles are up to date', async () => { 2346 | const config: IConfig = { 2347 | url: 'http://localhost/test', 2348 | clientKey: '12', 2349 | appName: 'web', 2350 | storageProvider: storage, 2351 | experimental: { 2352 | togglesStorageTTL: 60, 2353 | }, 2354 | }; 2355 | const client = new UnleashClient(config); 2356 | 2357 | const readySpy = jest.fn(); 2358 | client.on(EVENTS.READY, readySpy); 2359 | client.on(EVENTS.INIT, () => readySpy.mockClear()); 2360 | await client.start(); 2361 | expect(readySpy).toHaveBeenCalledTimes(1); 2362 | }); 2363 | 2364 | test('Should perform a fetch when context is updated, even if flags are up to date', async () => { 2365 | const config: IConfig = { 2366 | url: 'http://localhost/test', 2367 | clientKey: '12', 2368 | appName: 'web', 2369 | storageProvider: storage, 2370 | experimental: { 2371 | togglesStorageTTL: 60, 2372 | }, 2373 | }; 2374 | const client = new UnleashClient(config); 2375 | await client.start(); 2376 | let isEnabled = client.isEnabled('simpleToggle'); 2377 | expect(isEnabled).toBe(true); 2378 | await client.updateContext({ userId: '123' }); 2379 | expect(fetchMock).toHaveBeenCalledTimes(1); 2380 | isEnabled = client.isEnabled('simpleToggle'); 2381 | expect(isEnabled).toBe(false); 2382 | }); 2383 | 2384 | test('Should perform a fetch when context is updated and refreshInterval disabled, even if flags are up to date', async () => { 2385 | const config: IConfig = { 2386 | url: 'http://localhost/test', 2387 | clientKey: '12', 2388 | appName: 'web', 2389 | storageProvider: storage, 2390 | experimental: { 2391 | togglesStorageTTL: 60, 2392 | }, 2393 | refreshInterval: 0, 2394 | }; 2395 | const client = new UnleashClient(config); 2396 | await client.start(); 2397 | let isEnabled = client.isEnabled('simpleToggle'); 2398 | expect(isEnabled).toBe(true); 2399 | await client.updateContext({ userId: '123' }); 2400 | expect(fetchMock).toHaveBeenCalledTimes(1); 2401 | isEnabled = client.isEnabled('simpleToggle'); 2402 | expect(isEnabled).toBe(false); 2403 | }); 2404 | }); 2405 | }); 2406 | 2407 | describe('updateToggles', () => { 2408 | it('should not update toggles when not started', () => { 2409 | const config: IConfig = { 2410 | url: 'http://localhost/test', 2411 | clientKey: '12', 2412 | appName: 'web', 2413 | }; 2414 | const client = new UnleashClient(config); 2415 | 2416 | client.updateToggles(); 2417 | 2418 | expect(fetchMock).not.toHaveBeenCalled(); 2419 | }); 2420 | 2421 | it('should update toggles when started', async () => { 2422 | const config: IConfig = { 2423 | url: 'http://localhost/test', 2424 | clientKey: '12', 2425 | appName: 'web', 2426 | }; 2427 | const client = new UnleashClient(config); 2428 | 2429 | await client.start(); 2430 | fetchMock.mockClear(); 2431 | 2432 | client.updateToggles(); 2433 | 2434 | expect(fetchMock).toHaveBeenCalled(); 2435 | }); 2436 | 2437 | it('should wait for client readiness before the toggles update', async () => { 2438 | const config: IConfig = { 2439 | url: 'http://localhost/test', 2440 | clientKey: '12', 2441 | appName: 'web', 2442 | refreshInterval: 0, 2443 | }; 2444 | const client = new UnleashClient(config); 2445 | 2446 | client.start(); 2447 | 2448 | client.updateToggles(); 2449 | 2450 | expect(fetchMock).not.toHaveBeenCalled(); 2451 | 2452 | client.emit(EVENTS.READY); 2453 | 2454 | expect(fetchMock).toHaveBeenCalledTimes(1); 2455 | }); 2456 | }); 2457 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { TinyEmitter } from 'tiny-emitter'; 2 | import Metrics from './metrics'; 3 | import type IStorageProvider from './storage-provider'; 4 | import InMemoryStorageProvider from './storage-provider-inmemory'; 5 | import LocalStorageProvider from './storage-provider-local'; 6 | import EventsHandler from './events-handler'; 7 | import { 8 | computeContextHashValue, 9 | parseHeaders, 10 | urlWithContextAsQuery, 11 | } from './util'; 12 | import { uuidv4 } from './uuidv4'; 13 | 14 | const DEFINED_FIELDS = [ 15 | 'userId', 16 | 'sessionId', 17 | 'remoteAddress', 18 | 'currentTime', 19 | ] as const; 20 | type DefinedField = (typeof DEFINED_FIELDS)[number]; 21 | 22 | interface IStaticContext { 23 | appName: string; 24 | environment?: string; 25 | } 26 | 27 | interface IMutableContext { 28 | userId?: string; 29 | sessionId?: string; 30 | remoteAddress?: string; 31 | currentTime?: string; 32 | properties?: { 33 | [key: string]: string; 34 | }; 35 | } 36 | 37 | type IContext = IStaticContext & IMutableContext; 38 | 39 | const isDefinedContextField = (field: string): field is DefinedField => { 40 | return DEFINED_FIELDS.includes(field as DefinedField); 41 | }; 42 | 43 | interface IConfig extends IStaticContext { 44 | url: URL | string; 45 | clientKey: string; 46 | disableRefresh?: boolean; 47 | refreshInterval?: number; 48 | metricsInterval?: number; 49 | metricsIntervalInitial?: number; 50 | disableMetrics?: boolean; 51 | storageProvider?: IStorageProvider; 52 | context?: IMutableContext; 53 | fetch?: any; 54 | createAbortController?: () => AbortController | null; 55 | bootstrap?: IToggle[]; 56 | bootstrapOverride?: boolean; 57 | headerName?: string; 58 | customHeaders?: Record; 59 | impressionDataAll?: boolean; 60 | usePOSTrequests?: boolean; 61 | experimental?: IExperimentalConfig; 62 | } 63 | 64 | interface IExperimentalConfig { 65 | togglesStorageTTL?: number; 66 | metricsUrl?: URL | string; 67 | } 68 | 69 | interface IVariant { 70 | name: string; 71 | enabled: boolean; 72 | feature_enabled?: boolean; 73 | payload?: { 74 | type: string; 75 | value: string; 76 | }; 77 | } 78 | 79 | interface IToggle { 80 | name: string; 81 | enabled: boolean; 82 | variant: IVariant; 83 | impressionData: boolean; 84 | } 85 | 86 | export const EVENTS = { 87 | INIT: 'initialized', 88 | ERROR: 'error', 89 | READY: 'ready', 90 | UPDATE: 'update', 91 | IMPRESSION: 'impression', 92 | SENT: 'sent', 93 | RECOVERED: 'recovered', 94 | }; 95 | 96 | const IMPRESSION_EVENTS = { 97 | IS_ENABLED: 'isEnabled', 98 | GET_VARIANT: 'getVariant', 99 | }; 100 | 101 | const defaultVariant: IVariant = { 102 | name: 'disabled', 103 | enabled: false, 104 | feature_enabled: false, 105 | }; 106 | const storeKey = 'repo'; 107 | export const lastUpdateKey = 'repoLastUpdateTimestamp'; 108 | 109 | type SdkState = 'initializing' | 'healthy' | 'error'; 110 | 111 | type LastUpdateTerms = { 112 | key: string; 113 | timestamp: number; 114 | }; 115 | 116 | export const resolveFetch = () => { 117 | try { 118 | if (typeof window !== 'undefined' && 'fetch' in window) { 119 | return fetch.bind(window); 120 | } 121 | 122 | if ('fetch' in globalThis) { 123 | return fetch.bind(globalThis); 124 | } 125 | } catch (e) { 126 | console.error('Unleash failed to resolve "fetch"', e); 127 | } 128 | 129 | return undefined; 130 | }; 131 | 132 | const resolveAbortController = () => { 133 | try { 134 | if (typeof window !== 'undefined' && 'AbortController' in window) { 135 | return () => new window.AbortController(); 136 | } 137 | 138 | if ('fetch' in globalThis) { 139 | return () => new globalThis.AbortController(); 140 | } 141 | } catch (e) { 142 | console.error('Unleash failed to resolve "AbortController" factory', e); 143 | } 144 | }; 145 | 146 | export class UnleashClient extends TinyEmitter { 147 | private toggles: IToggle[] = []; 148 | private impressionDataAll: boolean; 149 | private context: IContext; 150 | private timerRef?: any; 151 | private storage: IStorageProvider; 152 | private refreshInterval: number; 153 | private url: URL; 154 | private clientKey: string; 155 | private etag = ''; 156 | private metrics: Metrics; 157 | private ready: Promise; 158 | private fetch: any; 159 | private createAbortController?: () => AbortController | null; 160 | private abortController?: AbortController | null; 161 | private bootstrap?: IToggle[]; 162 | private bootstrapOverride: boolean; 163 | private headerName: string; 164 | private eventsHandler: EventsHandler; 165 | private customHeaders: Record; 166 | private readyEventEmitted = false; 167 | private fetchedFromServer = false; 168 | private usePOSTrequests = false; 169 | private started = false; 170 | private sdkState: SdkState; 171 | private lastError: any; 172 | private experimental: IExperimentalConfig; 173 | private lastRefreshTimestamp: number; 174 | private connectionId: string; 175 | 176 | constructor({ 177 | storageProvider, 178 | url, 179 | clientKey, 180 | disableRefresh = false, 181 | refreshInterval = 30, 182 | metricsInterval = 30, 183 | metricsIntervalInitial = 2, 184 | disableMetrics = false, 185 | appName, 186 | environment = 'default', 187 | context, 188 | fetch = resolveFetch(), 189 | createAbortController = resolveAbortController(), 190 | bootstrap, 191 | bootstrapOverride = true, 192 | headerName = 'Authorization', 193 | customHeaders = {}, 194 | impressionDataAll = false, 195 | usePOSTrequests = false, 196 | experimental, 197 | }: IConfig) { 198 | super(); 199 | // Validations 200 | if (!url) { 201 | throw new Error('url is required'); 202 | } 203 | if (!clientKey) { 204 | throw new Error('clientKey is required'); 205 | } 206 | if (!appName) { 207 | throw new Error('appName is required.'); 208 | } 209 | this.eventsHandler = new EventsHandler(); 210 | this.impressionDataAll = impressionDataAll; 211 | this.toggles = bootstrap && bootstrap.length > 0 ? bootstrap : []; 212 | this.url = url instanceof URL ? url : new URL(url); 213 | this.clientKey = clientKey; 214 | this.headerName = headerName; 215 | this.customHeaders = customHeaders; 216 | this.storage = 217 | storageProvider || 218 | (typeof window !== 'undefined' 219 | ? new LocalStorageProvider() 220 | : new InMemoryStorageProvider()); 221 | this.refreshInterval = disableRefresh ? 0 : refreshInterval * 1000; 222 | this.context = { appName, environment, ...context }; 223 | this.usePOSTrequests = usePOSTrequests; 224 | this.sdkState = 'initializing'; 225 | 226 | let metricsUrl = experimental?.metricsUrl; 227 | if (metricsUrl && !(metricsUrl instanceof URL)) { 228 | metricsUrl = new URL(metricsUrl); 229 | } 230 | this.experimental = { 231 | ...experimental, 232 | metricsUrl, 233 | }; 234 | 235 | if ( 236 | experimental?.togglesStorageTTL && 237 | experimental?.togglesStorageTTL > 0 238 | ) { 239 | this.experimental.togglesStorageTTL = 240 | experimental.togglesStorageTTL * 1000; 241 | } 242 | 243 | this.lastRefreshTimestamp = 0; 244 | 245 | this.ready = new Promise((resolve) => { 246 | this.init() 247 | .then(resolve) 248 | .catch((error) => { 249 | console.error(error); 250 | this.sdkState = 'error'; 251 | this.emit(EVENTS.ERROR, error); 252 | this.lastError = error; 253 | resolve(); 254 | }); 255 | }); 256 | 257 | if (!fetch) { 258 | console.error( 259 | 'Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.' 260 | ); 261 | } 262 | if (!createAbortController) { 263 | console.error( 264 | 'Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.' 265 | ); 266 | } 267 | 268 | this.fetch = fetch; 269 | this.createAbortController = createAbortController; 270 | this.bootstrap = 271 | bootstrap && bootstrap.length > 0 ? bootstrap : undefined; 272 | this.bootstrapOverride = bootstrapOverride; 273 | 274 | this.connectionId = uuidv4(); 275 | 276 | this.metrics = new Metrics({ 277 | onError: this.emit.bind(this, EVENTS.ERROR), 278 | onSent: this.emit.bind(this, EVENTS.SENT), 279 | appName, 280 | metricsInterval, 281 | disableMetrics, 282 | url: this.experimental?.metricsUrl || this.url, 283 | clientKey, 284 | fetch, 285 | headerName, 286 | customHeaders, 287 | metricsIntervalInitial, 288 | connectionId: this.connectionId, 289 | }); 290 | } 291 | 292 | public getAllToggles(): IToggle[] { 293 | return [...this.toggles]; 294 | } 295 | 296 | public isEnabled(toggleName: string): boolean { 297 | const toggle = this.toggles.find((t) => t.name === toggleName); 298 | const enabled = toggle ? toggle.enabled : false; 299 | this.metrics.count(toggleName, enabled); 300 | 301 | if (toggle?.impressionData || this.impressionDataAll) { 302 | const event = this.eventsHandler.createImpressionEvent( 303 | this.context, 304 | enabled, 305 | toggleName, 306 | IMPRESSION_EVENTS.IS_ENABLED, 307 | toggle?.impressionData ?? undefined 308 | ); 309 | this.emit(EVENTS.IMPRESSION, event); 310 | } 311 | 312 | return enabled; 313 | } 314 | 315 | public getVariant(toggleName: string): IVariant { 316 | const toggle = this.toggles.find((t) => t.name === toggleName); 317 | const enabled = toggle?.enabled || false; 318 | const variant = toggle ? toggle.variant : defaultVariant; 319 | 320 | if (variant.name) { 321 | this.metrics.countVariant(toggleName, variant.name); 322 | } 323 | this.metrics.count(toggleName, enabled); 324 | if (toggle?.impressionData || this.impressionDataAll) { 325 | const event = this.eventsHandler.createImpressionEvent( 326 | this.context, 327 | enabled, 328 | toggleName, 329 | IMPRESSION_EVENTS.GET_VARIANT, 330 | toggle?.impressionData ?? undefined, 331 | variant.name 332 | ); 333 | this.emit(EVENTS.IMPRESSION, event); 334 | } 335 | return { ...variant, feature_enabled: enabled }; 336 | } 337 | 338 | public async updateToggles() { 339 | if (this.timerRef || this.fetchedFromServer) { 340 | await this.fetchToggles(); 341 | } else if (this.started) { 342 | await new Promise((resolve) => { 343 | const listener = () => { 344 | this.fetchToggles().then(() => { 345 | this.off(EVENTS.READY, listener); 346 | resolve(); 347 | }); 348 | }; 349 | this.once(EVENTS.READY, listener); 350 | }); 351 | } 352 | } 353 | 354 | public async updateContext(context: IMutableContext): Promise { 355 | // @ts-expect-error Give the user a nicer error message when 356 | // including static fields in the mutable context object 357 | if (context.appName || context.environment) { 358 | console.warn( 359 | "appName and environment are static. They can't be updated with updateContext." 360 | ); 361 | } 362 | const staticContext = { 363 | environment: this.context.environment, 364 | appName: this.context.appName, 365 | sessionId: this.context.sessionId, 366 | }; 367 | this.context = { ...staticContext, ...context }; 368 | 369 | await this.updateToggles(); 370 | } 371 | 372 | public getContext() { 373 | return { ...this.context }; 374 | } 375 | 376 | public setContextField(field: string, value: string) { 377 | if (isDefinedContextField(field)) { 378 | this.context = { ...this.context, [field]: value }; 379 | } else { 380 | const properties = { ...this.context.properties, [field]: value }; 381 | this.context = { ...this.context, properties }; 382 | } 383 | 384 | this.updateToggles(); 385 | } 386 | 387 | public removeContextField(field: string): void { 388 | if (isDefinedContextField(field)) { 389 | this.context = { ...this.context, [field]: undefined }; 390 | } else if (typeof this.context.properties === 'object') { 391 | delete this.context.properties[field]; 392 | } 393 | 394 | this.updateToggles(); 395 | } 396 | 397 | private setReady() { 398 | this.readyEventEmitted = true; 399 | this.emit(EVENTS.READY); 400 | } 401 | 402 | private async init(): Promise { 403 | const sessionId = await this.resolveSessionId(); 404 | this.context = { sessionId, ...this.context }; 405 | 406 | const storedToggles = (await this.storage.get(storeKey)) || []; 407 | this.lastRefreshTimestamp = await this.getLastRefreshTimestamp(); 408 | 409 | if ( 410 | this.bootstrap && 411 | (this.bootstrapOverride || storedToggles.length === 0) 412 | ) { 413 | await this.storage.save(storeKey, this.bootstrap); 414 | this.toggles = this.bootstrap; 415 | this.sdkState = 'healthy'; 416 | 417 | // Indicates that the bootstrap is fresh, and avoid the initial fetch 418 | await this.storeLastRefreshTimestamp(); 419 | 420 | this.setReady(); 421 | } else { 422 | this.toggles = storedToggles; 423 | } 424 | 425 | this.sdkState = 'healthy'; 426 | this.emit(EVENTS.INIT); 427 | } 428 | 429 | public async start(): Promise { 430 | this.started = true; 431 | if (this.timerRef) { 432 | console.error( 433 | 'Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again.' 434 | ); 435 | return; 436 | } 437 | await this.ready; 438 | this.metrics.start(); 439 | const interval = this.refreshInterval; 440 | 441 | await this.initialFetchToggles(); 442 | 443 | if (interval > 0) { 444 | this.timerRef = setInterval(() => this.fetchToggles(), interval); 445 | } 446 | } 447 | 448 | public stop(): void { 449 | if (this.timerRef) { 450 | clearInterval(this.timerRef); 451 | this.timerRef = undefined; 452 | } 453 | this.metrics.stop(); 454 | } 455 | 456 | public isReady(): boolean { 457 | return this.readyEventEmitted; 458 | } 459 | 460 | public getError() { 461 | return this.sdkState === 'error' ? this.lastError : undefined; 462 | } 463 | 464 | public sendMetrics() { 465 | return this.metrics.sendMetrics(); 466 | } 467 | 468 | private async resolveSessionId(): Promise { 469 | if (this.context.sessionId) { 470 | return this.context.sessionId; 471 | } 472 | 473 | let sessionId = await this.storage.get('sessionId'); 474 | if (!sessionId) { 475 | sessionId = Math.floor(Math.random() * 1_000_000_000); 476 | await this.storage.save('sessionId', sessionId.toString(10)); 477 | } 478 | return sessionId.toString(10); 479 | } 480 | 481 | private getHeaders() { 482 | return parseHeaders({ 483 | clientKey: this.clientKey, 484 | connectionId: this.connectionId, 485 | appName: this.context.appName, 486 | customHeaders: this.customHeaders, 487 | headerName: this.headerName, 488 | etag: this.etag, 489 | isPost: this.usePOSTrequests, 490 | }); 491 | } 492 | 493 | private async storeToggles(toggles: IToggle[]): Promise { 494 | this.toggles = toggles; 495 | this.emit(EVENTS.UPDATE); 496 | await this.storage.save(storeKey, toggles); 497 | } 498 | 499 | private isTogglesStorageTTLEnabled(): boolean { 500 | return !!( 501 | this.experimental?.togglesStorageTTL && 502 | this.experimental.togglesStorageTTL > 0 503 | ); 504 | } 505 | 506 | private isUpToDate(): boolean { 507 | if (!this.isTogglesStorageTTLEnabled()) { 508 | return false; 509 | } 510 | const now = Date.now(); 511 | 512 | const ttl = this.experimental?.togglesStorageTTL || 0; 513 | 514 | return ( 515 | this.lastRefreshTimestamp > 0 && 516 | this.lastRefreshTimestamp <= now && 517 | now - this.lastRefreshTimestamp <= ttl 518 | ); 519 | } 520 | 521 | private async getLastRefreshTimestamp(): Promise { 522 | if (this.isTogglesStorageTTLEnabled()) { 523 | const lastRefresh: LastUpdateTerms | undefined = 524 | await this.storage.get(lastUpdateKey); 525 | const contextHash = await computeContextHashValue(this.context); 526 | return lastRefresh?.key === contextHash ? lastRefresh.timestamp : 0; 527 | } 528 | return 0; 529 | } 530 | 531 | private async storeLastRefreshTimestamp(): Promise { 532 | if (this.isTogglesStorageTTLEnabled()) { 533 | this.lastRefreshTimestamp = Date.now(); 534 | 535 | const lastUpdateValue: LastUpdateTerms = { 536 | key: await computeContextHashValue(this.context), 537 | timestamp: this.lastRefreshTimestamp, 538 | }; 539 | await this.storage.save(lastUpdateKey, lastUpdateValue); 540 | } 541 | } 542 | 543 | private initialFetchToggles() { 544 | if (this.isUpToDate()) { 545 | if (!this.fetchedFromServer) { 546 | this.fetchedFromServer = true; 547 | this.setReady(); 548 | } 549 | return; 550 | } 551 | return this.fetchToggles(); 552 | } 553 | 554 | private async fetchToggles() { 555 | if (this.fetch) { 556 | // Check if abortController is already aborted before calling abort 557 | if (this.abortController && !this.abortController.signal.aborted) { 558 | this.abortController.abort(); 559 | } 560 | this.abortController = this.createAbortController?.(); 561 | const signal = this.abortController 562 | ? this.abortController.signal 563 | : undefined; 564 | 565 | try { 566 | const isPOST = this.usePOSTrequests; 567 | 568 | const url = isPOST 569 | ? this.url 570 | : urlWithContextAsQuery(this.url, this.context); 571 | const method = isPOST ? 'POST' : 'GET'; 572 | const body = isPOST 573 | ? JSON.stringify({ context: this.context }) 574 | : undefined; 575 | 576 | const response = await this.fetch(url.toString(), { 577 | method, 578 | cache: 'no-cache', 579 | headers: this.getHeaders(), 580 | body, 581 | signal, 582 | }); 583 | if (this.sdkState === 'error' && response.status < 400) { 584 | this.sdkState = 'healthy'; 585 | this.emit(EVENTS.RECOVERED); 586 | } 587 | 588 | if (response.ok) { 589 | this.etag = response.headers.get('ETag') || ''; 590 | const data = await response.json(); 591 | await this.storeToggles(data.toggles); 592 | 593 | if (this.sdkState !== 'healthy') { 594 | this.sdkState = 'healthy'; 595 | } 596 | if (!this.fetchedFromServer) { 597 | this.fetchedFromServer = true; 598 | this.setReady(); 599 | } 600 | this.storeLastRefreshTimestamp(); 601 | } else if (response.status === 304) { 602 | this.storeLastRefreshTimestamp(); 603 | } else { 604 | console.error( 605 | 'Unleash: Fetching feature toggles did not have an ok response' 606 | ); 607 | this.sdkState = 'error'; 608 | this.emit(EVENTS.ERROR, { 609 | type: 'HttpError', 610 | code: response.status, 611 | }); 612 | 613 | this.lastError = { 614 | type: 'HttpError', 615 | code: response.status, 616 | }; 617 | } 618 | } catch (e) { 619 | if ( 620 | !( 621 | typeof e === 'object' && 622 | e !== null && 623 | 'name' in e && 624 | e.name === 'AbortError' 625 | ) 626 | ) { 627 | console.error( 628 | 'Unleash: unable to fetch feature toggles', 629 | e 630 | ); 631 | this.sdkState = 'error'; 632 | this.emit(EVENTS.ERROR, e); 633 | this.lastError = e; 634 | } 635 | } finally { 636 | this.abortController = null; 637 | } 638 | } 639 | } 640 | } 641 | 642 | // export storage providers from root module 643 | export { type IStorageProvider, LocalStorageProvider, InMemoryStorageProvider }; 644 | 645 | export type { IConfig, IContext, IMutableContext, IVariant, IToggle }; 646 | -------------------------------------------------------------------------------- /src/metrics.test.ts: -------------------------------------------------------------------------------- 1 | import { FetchMock } from 'jest-fetch-mock'; 2 | import Metrics from './metrics'; 3 | import { getTypeSafeRequest, parseRequestBodyWithType } from './test'; 4 | 5 | jest.useFakeTimers(); 6 | 7 | const fetchMock = fetch as FetchMock; 8 | 9 | afterEach(() => { 10 | fetchMock.resetMocks(); 11 | jest.clearAllTimers(); 12 | }); 13 | 14 | test('should be disabled by flag disableMetrics', async () => { 15 | const metrics = new Metrics({ 16 | onError: console.error, 17 | appName: 'test', 18 | metricsInterval: 0, 19 | disableMetrics: true, 20 | url: 'http://localhost:3000', 21 | clientKey: '123', 22 | fetch: fetchMock, 23 | headerName: 'Authorization', 24 | metricsIntervalInitial: 0, 25 | connectionId: '123', 26 | }); 27 | 28 | metrics.count('foo', true); 29 | 30 | await metrics.sendMetrics(); 31 | 32 | expect(fetchMock.mock.calls.length).toEqual(0); 33 | }); 34 | 35 | test('should send metrics', async () => { 36 | const metrics = new Metrics({ 37 | onError: console.error, 38 | appName: 'test', 39 | metricsInterval: 0, 40 | disableMetrics: false, 41 | url: 'http://localhost:3000', 42 | clientKey: '123', 43 | fetch: fetchMock, 44 | headerName: 'Authorization', 45 | metricsIntervalInitial: 0, 46 | connectionId: '123', 47 | }); 48 | 49 | metrics.count('foo', true); 50 | metrics.count('foo', true); 51 | metrics.count('foo', false); 52 | metrics.count('bar', false); 53 | metrics.countVariant('foo', 'foo-variant'); 54 | metrics.countVariant('foo', 'foo-variant'); 55 | 56 | await metrics.sendMetrics(); 57 | 58 | expect(fetchMock.mock.calls.length).toEqual(1); 59 | 60 | /** Parse request and get its body with casted type */ 61 | const request = getTypeSafeRequest(fetchMock); 62 | const body = parseRequestBodyWithType<{ bucket: Metrics['bucket'] }>( 63 | request 64 | ); 65 | 66 | expect(body.bucket.toggles.foo.yes).toEqual(2); 67 | expect(body.bucket.toggles.foo.no).toEqual(1); 68 | expect(body.bucket.toggles.bar.yes).toEqual(0); 69 | expect(body.bucket.toggles.bar.no).toEqual(1); 70 | expect(body.bucket.toggles.foo.variants).toEqual({ 'foo-variant': 2 }); 71 | }); 72 | 73 | test('should send metrics with custom auth header', async () => { 74 | const metrics = new Metrics({ 75 | onError: console.error, 76 | appName: 'test', 77 | metricsInterval: 0, 78 | disableMetrics: false, 79 | url: 'http://localhost:3000', 80 | clientKey: '123', 81 | fetch: fetchMock, 82 | headerName: 'NotAuthorization', 83 | metricsIntervalInitial: 0, 84 | connectionId: '123', 85 | }); 86 | 87 | metrics.count('foo', true); 88 | await metrics.sendMetrics(); 89 | 90 | const requestBody = getTypeSafeRequest(fetchMock); 91 | 92 | expect(fetchMock.mock.calls.length).toEqual(1); 93 | expect(requestBody.headers).toMatchObject({ 94 | notauthorization: '123', 95 | }); 96 | }); 97 | 98 | test('Should send initial metrics after 2 seconds', () => { 99 | const metrics = new Metrics({ 100 | onError: console.error, 101 | appName: 'test', 102 | metricsInterval: 5, 103 | disableMetrics: false, 104 | url: 'http://localhost:3000', 105 | clientKey: '123', 106 | fetch: fetchMock, 107 | headerName: 'Authorization', 108 | metricsIntervalInitial: 2, 109 | connectionId: '123', 110 | }); 111 | 112 | metrics.start(); 113 | 114 | metrics.count('foo', true); 115 | metrics.count('foo', true); 116 | metrics.count('foo', false); 117 | metrics.count('bar', false); 118 | // Account for 2 second timeout before the set interval starts 119 | jest.advanceTimersByTime(2000); 120 | expect(fetchMock.mock.calls.length).toEqual(1); 121 | }); 122 | 123 | test('Should send initial metrics after 20 seconds, when metricsIntervalInitial is higher than metricsInterval', () => { 124 | const metrics = new Metrics({ 125 | onError: console.error, 126 | appName: 'test', 127 | metricsInterval: 5, 128 | disableMetrics: false, 129 | url: 'http://localhost:3000', 130 | clientKey: '123', 131 | fetch: fetchMock, 132 | headerName: 'Authorization', 133 | metricsIntervalInitial: 20, 134 | connectionId: '123', 135 | }); 136 | 137 | metrics.start(); 138 | 139 | metrics.count('foo', true); 140 | metrics.count('foo', true); 141 | metrics.count('foo', false); 142 | metrics.count('bar', false); 143 | // Account for 20 second timeout before the set interval starts 144 | jest.advanceTimersByTime(20000); 145 | expect(fetchMock.mock.calls.length).toEqual(1); 146 | }); 147 | 148 | test('Should send metrics for initial and after metrics interval', () => { 149 | const metrics = new Metrics({ 150 | onError: console.error, 151 | appName: 'test', 152 | metricsInterval: 5, 153 | disableMetrics: false, 154 | url: 'http://localhost:3000', 155 | clientKey: '123', 156 | fetch: fetchMock, 157 | headerName: 'Authorization', 158 | metricsIntervalInitial: 2, 159 | connectionId: '123', 160 | }); 161 | 162 | metrics.start(); 163 | 164 | metrics.count('foo', true); 165 | metrics.count('foo', true); 166 | metrics.count('foo', false); 167 | metrics.count('bar', false); 168 | // Account for 2 second timeout before the set interval starts 169 | jest.advanceTimersByTime(2000); 170 | metrics.count('foo', false); 171 | metrics.count('bar', false); 172 | jest.advanceTimersByTime(5000); 173 | expect(fetchMock.mock.calls.length).toEqual(2); 174 | }); 175 | 176 | test('Should not send initial metrics if disabled', () => { 177 | const metrics = new Metrics({ 178 | onError: console.error, 179 | appName: 'test', 180 | metricsInterval: 5, 181 | disableMetrics: false, 182 | url: 'http://localhost:3000', 183 | clientKey: '123', 184 | fetch: fetchMock, 185 | headerName: 'Authorization', 186 | metricsIntervalInitial: 0, 187 | connectionId: '123', 188 | }); 189 | 190 | metrics.start(); 191 | 192 | metrics.count('foo', true); 193 | metrics.count('foo', true); 194 | metrics.count('foo', false); 195 | metrics.count('bar', false); 196 | // Account for 2 second timeout before the set interval starts 197 | jest.advanceTimersByTime(2000); 198 | expect(fetchMock.mock.calls.length).toEqual(0); 199 | }); 200 | 201 | test('should send metrics based on timer interval', async () => { 202 | const metrics = new Metrics({ 203 | onError: console.error, 204 | appName: 'test', 205 | metricsInterval: 5, 206 | disableMetrics: false, 207 | url: new URL('http://localhost:3000'), 208 | clientKey: '123', 209 | fetch: fetchMock, 210 | headerName: 'Authorization', 211 | metricsIntervalInitial: 2, 212 | connectionId: '123', 213 | }); 214 | 215 | metrics.start(); 216 | 217 | metrics.count('foo', true); 218 | metrics.count('foo', true); 219 | metrics.count('foo', false); 220 | metrics.count('bar', false); 221 | // Account for 2 second timeout before the set interval starts 222 | jest.advanceTimersByTime(2000); 223 | 224 | metrics.count('foo', true); 225 | metrics.count('foo', true); 226 | metrics.count('foo', false); 227 | metrics.count('bar', false); 228 | // Fill bucket and advance the interval 229 | jest.advanceTimersByTime(5000); 230 | 231 | metrics.count('foo', true); 232 | metrics.count('foo', true); 233 | metrics.count('foo', false); 234 | metrics.count('bar', false); 235 | // Fill bucket and advance the interval 236 | jest.advanceTimersByTime(5000); 237 | 238 | expect(fetchMock.mock.calls.length).toEqual(3); 239 | }); 240 | 241 | describe('Custom headers for metrics', () => { 242 | const runMetrics = async (customHeaders: Record) => { 243 | const metrics = new Metrics({ 244 | onError: console.error, 245 | appName: 'test', 246 | metricsInterval: 5, 247 | disableMetrics: false, 248 | url: 'http://localhost:3000', 249 | clientKey: '123', 250 | fetch: fetchMock, 251 | headerName: 'Authorization', 252 | customHeaders, 253 | connectionId: '123', 254 | metricsIntervalInitial: 2, 255 | }); 256 | 257 | metrics.count('foo', true); 258 | await metrics.sendMetrics(); 259 | 260 | return getTypeSafeRequest(fetchMock); 261 | }; 262 | 263 | test('Should apply any custom headers to the metrics request', async () => { 264 | const customHeaders = { 265 | 'x-custom-header': '123', 266 | }; 267 | 268 | const requestBody = await runMetrics(customHeaders); 269 | expect(requestBody.headers).toMatchObject(customHeaders); 270 | }); 271 | 272 | test('Custom headers should override preset headers', async () => { 273 | const customHeaders = { 274 | authorization: 'definitely-not-the-client-key', 275 | }; 276 | 277 | const requestBody = await runMetrics(customHeaders); 278 | expect(requestBody.headers).toMatchObject(customHeaders); 279 | }); 280 | 281 | test('Empty custom headers do not override preset headers on collision', async () => { 282 | const customHeaders = { 283 | Authorization: null, 284 | }; 285 | 286 | // @ts-expect-error this shouldn't be allowed in TS, but there's 287 | // nothing stopping you from doing it in JS. 288 | const requestBody = await runMetrics(customHeaders); 289 | expect(requestBody.headers).not.toMatchObject(customHeaders); 290 | }); 291 | 292 | test.each([null, undefined])( 293 | 'Custom headers that are "%s" should not be sent', 294 | async (emptyValue) => { 295 | const customHeaders = { 296 | 'invalid-header': emptyValue, 297 | }; 298 | 299 | // @ts-expect-error this shouldn't be allowed in TS, but there's 300 | // nothing stopping you from doing it in JS. 301 | const requestBody = await runMetrics(customHeaders); 302 | 303 | expect(requestBody.headers).not.toMatchObject(customHeaders); 304 | } 305 | ); 306 | 307 | test('Should use case-insensitive headers', () => { 308 | const metrics = new Metrics({ 309 | onError: console.error, 310 | appName: 'test', 311 | metricsInterval: 5, 312 | disableMetrics: false, 313 | url: 'http://localhost:3000', 314 | clientKey: '123', 315 | fetch: fetchMock, 316 | headerName: 'Authorization', 317 | customHeaders: { 318 | 'Custom-Header': '123', 319 | 'custom-header': '456', 320 | 'unleash-APPname': 'override', 321 | 'unleash-connection-id': 'override', 322 | }, 323 | connectionId: '123', 324 | metricsIntervalInitial: 2, 325 | }); 326 | 327 | metrics.count('foo', true); 328 | metrics.sendMetrics(); 329 | 330 | const requestBody = getTypeSafeRequest(fetchMock); 331 | expect(requestBody.headers).toMatchObject({ 332 | 'custom-header': '456', 333 | 'unleash-appname': 'override', 334 | 'unleash-connection-id': '123', 335 | }); 336 | }); 337 | }); 338 | -------------------------------------------------------------------------------- /src/metrics.ts: -------------------------------------------------------------------------------- 1 | // Simplified version of: https://github.com/Unleash/unleash-client-node/blob/main/src/metrics.ts 2 | 3 | import { parseHeaders } from './util'; 4 | 5 | export interface MetricsOptions { 6 | onError: OnError; 7 | onSent?: OnSent; 8 | appName: string; 9 | metricsInterval: number; 10 | disableMetrics?: boolean; 11 | url: URL | string; 12 | clientKey: string; 13 | fetch: any; 14 | headerName: string; 15 | customHeaders?: Record; 16 | metricsIntervalInitial: number; 17 | connectionId: string; 18 | } 19 | 20 | interface VariantBucket { 21 | [s: string]: number; 22 | } 23 | 24 | interface Bucket { 25 | start: Date; 26 | stop: Date | null; 27 | toggles: { 28 | [s: string]: { yes: number; no: number; variants: VariantBucket }; 29 | }; 30 | } 31 | 32 | interface Payload { 33 | bucket: Bucket; 34 | appName: string; 35 | instanceId: string; 36 | } 37 | 38 | type OnError = (error: unknown) => void; 39 | type OnSent = (payload: Payload) => void; 40 | // eslint-disable-next-line @typescript-eslint/no-empty-function 41 | const doNothing = () => {}; 42 | 43 | export default class Metrics { 44 | private onError: OnError; 45 | private onSent: OnSent; 46 | private bucket: Bucket; 47 | private appName: string; 48 | private metricsInterval: number; 49 | private disabled: boolean; 50 | private url: URL; 51 | private clientKey: string; 52 | private timer: any; 53 | private fetch: any; 54 | private headerName: string; 55 | private customHeaders: Record; 56 | private metricsIntervalInitial: number; 57 | private connectionId: string; 58 | 59 | constructor({ 60 | onError, 61 | onSent, 62 | appName, 63 | metricsInterval, 64 | disableMetrics = false, 65 | url, 66 | clientKey, 67 | fetch, 68 | headerName, 69 | customHeaders = {}, 70 | metricsIntervalInitial, 71 | connectionId, 72 | }: MetricsOptions) { 73 | this.onError = onError; 74 | this.onSent = onSent || doNothing; 75 | this.disabled = disableMetrics; 76 | this.metricsInterval = metricsInterval * 1000; 77 | this.metricsIntervalInitial = metricsIntervalInitial * 1000; 78 | this.appName = appName; 79 | this.url = url instanceof URL ? url : new URL(url); 80 | this.clientKey = clientKey; 81 | this.bucket = this.createEmptyBucket(); 82 | this.fetch = fetch; 83 | this.headerName = headerName; 84 | this.customHeaders = customHeaders; 85 | this.connectionId = connectionId; 86 | } 87 | 88 | public start() { 89 | if (this.disabled) { 90 | return false; 91 | } 92 | 93 | if ( 94 | typeof this.metricsInterval === 'number' && 95 | this.metricsInterval > 0 96 | ) { 97 | if (this.metricsIntervalInitial > 0) { 98 | setTimeout(() => { 99 | this.startTimer(); 100 | this.sendMetrics(); 101 | }, this.metricsIntervalInitial); 102 | } else { 103 | this.startTimer(); 104 | } 105 | } 106 | } 107 | 108 | public stop() { 109 | if (this.timer) { 110 | clearInterval(this.timer); 111 | delete this.timer; 112 | } 113 | } 114 | 115 | public createEmptyBucket(): Bucket { 116 | return { 117 | start: new Date(), 118 | stop: null, 119 | toggles: {}, 120 | }; 121 | } 122 | 123 | private getHeaders() { 124 | return parseHeaders({ 125 | clientKey: this.clientKey, 126 | appName: this.appName, 127 | connectionId: this.connectionId, 128 | customHeaders: this.customHeaders, 129 | headerName: this.headerName, 130 | isPost: true, 131 | }); 132 | } 133 | 134 | public async sendMetrics(): Promise { 135 | /* istanbul ignore next if */ 136 | 137 | const url = `${this.url}/client/metrics`; 138 | const payload = this.getPayload(); 139 | 140 | if (this.bucketIsEmpty(payload)) { 141 | return; 142 | } 143 | 144 | try { 145 | await this.fetch(url, { 146 | cache: 'no-cache', 147 | method: 'POST', 148 | headers: this.getHeaders(), 149 | body: JSON.stringify(payload), 150 | }); 151 | this.onSent(payload); 152 | } catch (e) { 153 | console.error('Unleash: unable to send feature metrics', e); 154 | this.onError(e); 155 | } 156 | } 157 | 158 | public count(name: string, enabled: boolean): boolean { 159 | if (this.disabled || !this.bucket) { 160 | return false; 161 | } 162 | this.assertBucket(name); 163 | this.bucket.toggles[name][enabled ? 'yes' : 'no']++; 164 | return true; 165 | } 166 | 167 | public countVariant(name: string, variant: string): boolean { 168 | if (this.disabled || !this.bucket) { 169 | return false; 170 | } 171 | this.assertBucket(name); 172 | if (this.bucket.toggles[name].variants[variant]) { 173 | this.bucket.toggles[name].variants[variant] += 1; 174 | } else { 175 | this.bucket.toggles[name].variants[variant] = 1; 176 | } 177 | return true; 178 | } 179 | 180 | private assertBucket(name: string) { 181 | if (this.disabled || !this.bucket) { 182 | return false; 183 | } 184 | if (!this.bucket.toggles[name]) { 185 | this.bucket.toggles[name] = { 186 | yes: 0, 187 | no: 0, 188 | variants: {}, 189 | }; 190 | } 191 | } 192 | 193 | private startTimer(): void { 194 | this.timer = setInterval(() => { 195 | this.sendMetrics(); 196 | }, this.metricsInterval); 197 | } 198 | 199 | private bucketIsEmpty(payload: Payload) { 200 | return Object.keys(payload.bucket.toggles).length === 0; 201 | } 202 | 203 | private getPayload(): Payload { 204 | const bucket = { ...this.bucket, stop: new Date() }; 205 | this.bucket = this.createEmptyBucket(); 206 | 207 | return { 208 | bucket, 209 | appName: this.appName, 210 | instanceId: 'browser', 211 | }; 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/storage-provider-inmemory.test.ts: -------------------------------------------------------------------------------- 1 | import InMemoryStorageProvider from './storage-provider-inmemory'; 2 | 3 | describe('InMemoryStorageProvider', () => { 4 | it('should store and retrieve arbitrary values by key', async () => { 5 | const store = new InMemoryStorageProvider(); 6 | 7 | await store.save('key1', 'value1'); 8 | await store.save('key2', { value2: 'true' }); 9 | await store.save('key3', ['value3']); 10 | await store.save('key4', true); 11 | 12 | expect(await store.get('key1')).toBe('value1'); 13 | expect(await store.get('key2')).toMatchObject({ value2: 'true' }); 14 | expect(await store.get('key3')).toMatchObject(['value3']); 15 | expect(await store.get('key4')).toBe(true); 16 | }); 17 | 18 | it('should return undefined for empty value', async () => { 19 | const store = new InMemoryStorageProvider(); 20 | 21 | expect(await store.get('notDefinedKey')).toBe(undefined); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/storage-provider-inmemory.ts: -------------------------------------------------------------------------------- 1 | import type IStorageProvider from './storage-provider'; 2 | 3 | export default class InMemoryStorageProvider implements IStorageProvider { 4 | private store = new Map(); 5 | 6 | public async save(name: string, data: any) { 7 | this.store.set(name, data); 8 | } 9 | 10 | public async get(name: string) { 11 | return this.store.get(name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/storage-provider-local.test.ts: -------------------------------------------------------------------------------- 1 | import LocalStorageProvider from './storage-provider-local'; 2 | 3 | describe('LocalStorageProvider', () => { 4 | it('should store and retrieve arbitrary values by key', async () => { 5 | const store = new LocalStorageProvider(); 6 | 7 | await store.save('key1', 'value1'); 8 | await store.save('key2', { value2: 'true' }); 9 | await store.save('key3', ['value3']); 10 | await store.save('key4', true); 11 | 12 | expect(await store.get('key1')).toBe('value1'); 13 | expect(await store.get('key2')).toMatchObject({ value2: 'true' }); 14 | expect(await store.get('key3')).toMatchObject(['value3']); 15 | expect(await store.get('key4')).toBe(true); 16 | }); 17 | 18 | it('should support custom storage key', async () => { 19 | const store1 = new LocalStorageProvider('custom-storage-key'); 20 | const store2 = new LocalStorageProvider('custom-storage-key'); 21 | const store3 = new LocalStorageProvider('another-custom-storage-key'); 22 | 23 | await store1.save('key1', 'value1'); 24 | 25 | expect(await store1.get('key1')).toBe('value1'); 26 | expect(await store2.get('key1')).toBe('value1'); 27 | expect(await store3.get('key1')).toBe(undefined); 28 | }); 29 | 30 | it('should return undefined for empty value', async () => { 31 | const store = new LocalStorageProvider(); 32 | expect(await store.get('notDefinedKey')).toBe(undefined); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /src/storage-provider-local.ts: -------------------------------------------------------------------------------- 1 | import type IStorageProvider from './storage-provider'; 2 | 3 | export default class LocalStorageProvider implements IStorageProvider { 4 | private prefix: string; 5 | 6 | constructor(name = 'unleash:repository') { 7 | this.prefix = name; 8 | } 9 | 10 | public async save(name: string, data: any) { 11 | const repo = JSON.stringify(data); 12 | const key = `${this.prefix}:${name}`; 13 | try { 14 | window.localStorage.setItem(key, repo); 15 | } catch (ex) { 16 | console.error(ex); 17 | } 18 | } 19 | 20 | public get(name: string) { 21 | try { 22 | const key = `${this.prefix}:${name}`; 23 | const data = window.localStorage.getItem(key); 24 | return data ? JSON.parse(data) : undefined; 25 | } catch (e) { 26 | console.error(e); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/storage-provider.ts: -------------------------------------------------------------------------------- 1 | export default interface IStorageProvider { 2 | save: (name: string, data: any) => Promise; 3 | get: (name: string) => Promise; 4 | } 5 | -------------------------------------------------------------------------------- /src/test/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | unleash-proxy-client-js manual test 6 | 7 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/test/index.ts: -------------------------------------------------------------------------------- 1 | import type { FetchMock } from 'jest-fetch-mock'; 2 | 3 | /** 4 | * Extract request body from given `FetchMock` object. 5 | * @param fetchedMock - mocked fetch body to get the request body from 6 | * @param callIndex - index of call in given `fetcheMock` 7 | */ 8 | function getTypeSafeRequest( 9 | fetchedMock: FetchMock, 10 | callIndex: number | undefined = 0 11 | ): RequestInit { 12 | const mockedCall = fetchedMock.mock.calls[callIndex]; 13 | const [, mockedReq] = mockedCall; 14 | const typeSafeRequest = mockedReq ?? {}; 15 | 16 | return typeSafeRequest; 17 | } 18 | 19 | /** 20 | * Extract request url from given `FetchMock` object. 21 | * @param fetchedMock - mocked fetch body to get the request url from 22 | * @param callIndex - index of call in given `fetcheMock` 23 | */ 24 | function getTypeSafeRequestUrl( 25 | fetchedMock: FetchMock, 26 | callIndex: number | undefined = 0 27 | ): string { 28 | const mockedCall = fetchedMock.mock.calls[callIndex]; 29 | const [url] = mockedCall; 30 | 31 | return url as string; 32 | } 33 | 34 | /** 35 | * parses given `RequestInit` with `JSON.parse()` and return 36 | * its body with passed type. 37 | */ 38 | function parseRequestBodyWithType(requestBody: RequestInit): T { 39 | const body = JSON.parse(`${requestBody.body}`) as T; 40 | 41 | return body; 42 | } 43 | 44 | export { getTypeSafeRequest, getTypeSafeRequestUrl, parseRequestBodyWithType }; 45 | -------------------------------------------------------------------------------- /src/test/testdata.json: -------------------------------------------------------------------------------- 1 | { 2 | "toggles": [ 3 | { 4 | "name": "variantToggle", 5 | "enabled": true, 6 | "impressionData": true, 7 | "variant": { 8 | "name": "green", 9 | "payload": { 10 | "type": "string", 11 | "value": "some-text" 12 | }, 13 | "enabled": true, 14 | "feature_enabled": true 15 | } 16 | }, 17 | { 18 | "name": "featureToggle", 19 | "enabled": true, 20 | "impressionData": true, 21 | "variant": { 22 | "name": "disabled", 23 | "enabled": false, 24 | "feature_enabled": true 25 | } 26 | }, 27 | { 28 | "name": "simpleToggle", 29 | "enabled": true, 30 | "impressionData": true 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /src/util.test.ts: -------------------------------------------------------------------------------- 1 | import type { IContext } from '.'; 2 | import { 3 | computeContextHashValue, 4 | contextString, 5 | urlWithContextAsQuery, 6 | parseHeaders, 7 | } from './util'; 8 | 9 | test('should not add paramters to URL', async () => { 10 | const someUrl = new URL('https://test.com'); 11 | 12 | //@ts-expect-error on purpose for testing! 13 | const result = urlWithContextAsQuery(someUrl, {}); 14 | 15 | expect(result.toString()).toBe('https://test.com/'); 16 | }); 17 | 18 | test('should add context as query params', async () => { 19 | const someUrl = new URL('https://test.com'); 20 | 21 | const result = urlWithContextAsQuery(someUrl, { 22 | appName: 'test', 23 | userId: '1234A', 24 | }); 25 | 26 | expect(result.toString()).toBe( 27 | 'https://test.com/?appName=test&userId=1234A' 28 | ); 29 | }); 30 | 31 | test('should add context properties as query params', async () => { 32 | const someUrl = new URL('https://test.com'); 33 | 34 | const result = urlWithContextAsQuery(someUrl, { 35 | appName: 'test', 36 | userId: '1234A', 37 | properties: { custom1: 'test', custom2: 'test2' }, 38 | }); 39 | 40 | expect(result.toString()).toBe( 41 | 'https://test.com/?appName=test&userId=1234A&properties%5Bcustom1%5D=test&properties%5Bcustom2%5D=test2' 42 | ); 43 | }); 44 | 45 | test('should exclude context properties that are null or undefined', async () => { 46 | const someUrl = new URL('https://test.com'); 47 | 48 | const result = urlWithContextAsQuery(someUrl, { 49 | appName: 'test', 50 | userId: undefined, 51 | properties: { 52 | custom1: 'test', 53 | custom2: 'test2', 54 | //@ts-expect-error this shouldn't be allowed if you're using TS, but 55 | //you could probably force it 56 | custom3: null, 57 | //@ts-expect-error same as the null property above 58 | custom4: undefined, 59 | }, 60 | }); 61 | 62 | expect(result.toString()).toBe( 63 | 'https://test.com/?appName=test&properties%5Bcustom1%5D=test&properties%5Bcustom2%5D=test2' 64 | ); 65 | }); 66 | 67 | describe('contextString', () => { 68 | test('Should return value for a simple object', () => { 69 | const obj: IContext = { 70 | appName: '1', 71 | currentTime: '2', 72 | environment: '3', 73 | userId: '4', 74 | }; 75 | const hashValue = contextString(obj); 76 | expect(hashValue).toBe( 77 | '[[["appName","1"],["currentTime","2"],["environment","3"],["userId","4"]],[]]' 78 | ); 79 | }); 80 | 81 | test('Should sort an object with not sorted keys', () => { 82 | const obj: IContext = { 83 | userId: '4', 84 | appName: '1', 85 | environment: '3', 86 | currentTime: '2024-08-05T11:00:00.000Z', 87 | }; 88 | const hashValue = contextString(obj); 89 | expect(hashValue).toBe( 90 | '[[["appName","1"],["currentTime","2024-08-05T11:00:00.000Z"],["environment","3"],["userId","4"]],[]]' 91 | ); 92 | }); 93 | 94 | test('Should sort an object with not sorted properties', () => { 95 | const obj: IContext = { 96 | appName: '1', 97 | properties: { d: '4', c: '3' }, 98 | currentTime: '2', 99 | }; 100 | const hashValue = contextString(obj); 101 | expect(hashValue).toBe( 102 | '[[["appName","1"],["currentTime","2"]],[["c","3"],["d","4"]]]' 103 | ); 104 | }); 105 | }); 106 | 107 | describe('computeContextHashValue', () => { 108 | test('Should return SHA-256 representation', async () => { 109 | const obj: IContext = { 110 | appName: '1', 111 | currentTime: '2', 112 | environment: '3', 113 | userId: '4', 114 | }; 115 | 116 | expect(computeContextHashValue(obj)).resolves.toBe( 117 | // FIXME: Jest (JSDOM) doesn't have TextEncoder nor crypto.subtle 118 | '[[["appName","1"],["currentTime","2"],["environment","3"],["userId","4"]],[]]' 119 | // '70cff0d989f07f1bd8f29599b3d8d55d511a8a0718d02c6bc78894512e78d571' 120 | ); 121 | }); 122 | }); 123 | 124 | describe('parseHeaders', () => { 125 | const clientKey = 'test-client-key'; 126 | const appName = 'appName'; 127 | const connectionId = '1234-5678'; 128 | 129 | test('should set basic headers correctly', () => { 130 | const result = parseHeaders({ 131 | clientKey, 132 | appName, 133 | connectionId, 134 | }); 135 | 136 | expect(result).toEqual({ 137 | authorization: clientKey, 138 | 'unleash-sdk': 'unleash-client-js:__VERSION__', 139 | 'unleash-appname': appName, 140 | accept: 'application/json', 141 | 'unleash-connection-id': connectionId, 142 | }); 143 | }); 144 | 145 | test('should set custom client key header name', () => { 146 | const result = parseHeaders({ 147 | clientKey, 148 | appName, 149 | connectionId, 150 | headerName: 'auth', 151 | }); 152 | 153 | expect(result).toMatchObject({ auth: clientKey }); 154 | expect(Object.keys(result)).not.toContain('authorization'); 155 | }); 156 | 157 | test('should add custom headers', () => { 158 | const customHeaders = { 159 | 'custom-header': 'custom-value', 160 | 'unleash-connection-id': 'should-not-be-overwritten', 161 | 'unleash-appname': 'new-app-name', 162 | }; 163 | const result = parseHeaders({ 164 | clientKey, 165 | appName, 166 | connectionId, 167 | customHeaders, 168 | }); 169 | 170 | expect(Object.keys(result)).toHaveLength(6); 171 | expect(result).toMatchObject({ 172 | 'custom-header': 'custom-value', 173 | 'unleash-connection-id': connectionId, 174 | 'unleash-appname': 'new-app-name', 175 | }); 176 | }); 177 | 178 | test('should include etag if provided', () => { 179 | const etag = '12345'; 180 | const result = parseHeaders({ 181 | clientKey, 182 | appName, 183 | connectionId, 184 | etag, 185 | }); 186 | 187 | expect(result['if-none-match']).toBe(etag); 188 | }); 189 | 190 | test('should handle custom headers in a case-insensitive way and normalize them', () => { 191 | const customHeaders = { 192 | 'custom-HEADER': 'custom-value-1', 193 | 'Custom-Header': 'custom-value-2', 194 | }; 195 | const result = parseHeaders({ 196 | clientKey, 197 | appName, 198 | connectionId, 199 | customHeaders, 200 | }); 201 | 202 | expect(result).toMatchObject({ 203 | 'custom-header': 'custom-value-2', 204 | }); 205 | }); 206 | 207 | test('should ignore null or undefined custom headers', () => { 208 | const customHeaders = { 209 | header1: 'value1', 210 | header2: null as any, 211 | header3: undefined as any, 212 | }; 213 | const result = parseHeaders({ 214 | clientKey, 215 | appName, 216 | connectionId, 217 | customHeaders, 218 | }); 219 | 220 | expect(result).toEqual( 221 | expect.not.objectContaining({ 222 | header2: expect.anything(), 223 | header3: expect.anything(), 224 | }) 225 | ); 226 | }); 227 | 228 | test('should include content-type for POST requests', () => { 229 | const result = parseHeaders({ 230 | clientKey, 231 | appName, 232 | connectionId, 233 | isPost: true, 234 | }); 235 | 236 | expect(result['content-type']).toBe('application/json'); 237 | }); 238 | }); 239 | -------------------------------------------------------------------------------- /src/util.ts: -------------------------------------------------------------------------------- 1 | import { IContext } from '.'; 2 | import { sdkVersion } from './version'; 3 | 4 | export const notNullOrUndefined = ([, value]: [string, string]) => 5 | value !== undefined && value !== null; 6 | 7 | export const urlWithContextAsQuery = (url: URL, context: IContext) => { 8 | const urlWithQuery = new URL(url.toString()); 9 | // Add context information to url search params. If the properties 10 | // object is included in the context, flatten it into the search params 11 | // e.g. /?...&property.param1=param1Value&property.param2=param2Value 12 | Object.entries(context) 13 | .filter(notNullOrUndefined) 14 | .forEach(([contextKey, contextValue]) => { 15 | if (contextKey === 'properties' && contextValue) { 16 | Object.entries(contextValue) 17 | .filter(notNullOrUndefined) 18 | .forEach(([propertyKey, propertyValue]) => 19 | urlWithQuery.searchParams.append( 20 | `properties[${propertyKey}]`, 21 | propertyValue 22 | ) 23 | ); 24 | } else { 25 | urlWithQuery.searchParams.append(contextKey, contextValue); 26 | } 27 | }); 28 | return urlWithQuery; 29 | }; 30 | 31 | export const contextString = (context: IContext): string => { 32 | const { properties = {}, ...fields } = context; 33 | 34 | const sortEntries = (record: Record) => 35 | Object.entries(record).sort(([a], [b]) => 36 | a.localeCompare(b, undefined) 37 | ); 38 | 39 | return JSON.stringify([sortEntries(fields), sortEntries(properties)]); 40 | }; 41 | 42 | const sha256 = async (input: string): Promise => { 43 | const cryptoSubtle = 44 | typeof globalThis !== 'undefined' && globalThis.crypto?.subtle 45 | ? globalThis.crypto?.subtle 46 | : undefined; 47 | 48 | if ( 49 | typeof TextEncoder === 'undefined' || 50 | !cryptoSubtle?.digest || 51 | typeof Uint8Array === 'undefined' 52 | ) { 53 | throw new Error('Hashing function not available'); 54 | } 55 | 56 | const msgUint8 = new TextEncoder().encode(input); 57 | const hashBuffer = await cryptoSubtle.digest('SHA-256', msgUint8); 58 | const hexString = Array.from(new Uint8Array(hashBuffer)) 59 | .map((x) => x.toString(16).padStart(2, '0')) 60 | .join(''); 61 | return hexString; 62 | }; 63 | 64 | export const computeContextHashValue = async (obj: IContext) => { 65 | const value = contextString(obj); 66 | 67 | try { 68 | const hash = await sha256(value); 69 | return hash; 70 | } catch { 71 | return value; 72 | } 73 | }; 74 | 75 | export const parseHeaders = ({ 76 | clientKey, 77 | appName, 78 | connectionId, 79 | customHeaders, 80 | headerName = 'authorization', 81 | etag, 82 | isPost, 83 | }: { 84 | clientKey: string; 85 | connectionId: string; 86 | appName: string; 87 | customHeaders?: Record; 88 | headerName?: string; 89 | etag?: string; 90 | isPost?: boolean; 91 | }): Record => { 92 | const headers: Record = { 93 | accept: 'application/json', 94 | [headerName.toLocaleLowerCase()]: clientKey, 95 | 'unleash-sdk': sdkVersion, 96 | 'unleash-appname': appName, 97 | }; 98 | 99 | if (isPost) { 100 | headers['content-type'] = 'application/json'; 101 | } 102 | 103 | if (etag) { 104 | headers['if-none-match'] = etag; 105 | } 106 | 107 | Object.entries(customHeaders || {}) 108 | .filter(notNullOrUndefined) 109 | .forEach( 110 | ([name, value]) => (headers[name.toLocaleLowerCase()] = value) 111 | ); 112 | 113 | headers['unleash-connection-id'] = connectionId; 114 | 115 | return headers; 116 | }; 117 | -------------------------------------------------------------------------------- /src/uuidv4.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This function generates a UUID using Math.random(). 3 | * The distribution of unique values is not guaranteed to be as robust 4 | * as with a crypto module but works across all platforms (Node, React Native, browser JS). 5 | * 6 | * We use it for connection id generation which is not critical for security. 7 | */ 8 | export const uuidv4 = (): string => { 9 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { 10 | const r = (Math.random() * 16) | 0; 11 | const v = c === 'x' ? r : (r & 0x3) | 0x8; 12 | return v.toString(16); 13 | }); 14 | }; 15 | -------------------------------------------------------------------------------- /src/version.ts: -------------------------------------------------------------------------------- 1 | export const sdkVersion = `unleash-client-js:__VERSION__`; 2 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 7 | "lib": ["es6"], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | "sourceMap": true, /* Generates corresponding '.map' file. */ 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | "outDir": "build/cjs", /* Redirect output structure to the directory. */ 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true, /* Enable all strict type-checking options. */ 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 37 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 38 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 39 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 40 | 41 | /* Module Resolution Options */ 42 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "resolveJsonModule": true, 50 | //"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 51 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 52 | //"allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 53 | 54 | /* Source Map Options */ 55 | "sourceRoot": "../src", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 56 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 57 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 58 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 59 | 60 | /* Experimental Options */ 61 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 62 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 63 | }, 64 | "exclude": [ 65 | "node_modules", 66 | "src/**/*.test.ts", 67 | "./build/**/*", 68 | "src/test/index.ts" 69 | ] 70 | } 71 | --------------------------------------------------------------------------------