Skip to content

feat(browser-sdk,react-sdk): check events #316

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
aee63d5
fix(node-sdk): update Feature type to support undefined config
pavkam Feb 4, 2025
2029f91
chore(node-sdk): bump version to 1.6.0-alpha.3
pavkam Feb 5, 2025
c59474a
feat(browser-sdk): enhance feature flag and configuration tracking
pavkam Feb 4, 2025
5bc3816
feat(browser-sdk): improve feature flag event tracking details
pavkam Feb 5, 2025
d3c8ffa
refactor(react-sdk): simplify feature flag retrieval and event tracking
pavkam Feb 5, 2025
5d62397
feat(node-sdk): enhance feature flag event tracking with config and e…
pavkam Feb 5, 2025
e09227d
feat(node-sdk): include rule evaluation details in feature flag response
pavkam Feb 5, 2025
2c3c751
refactor(node-sdk): improve feature flag event tracking performance a…
pavkam Feb 5, 2025
cbb7140
refactor(node-sdk): improve missing context fields warning mechanism
pavkam Feb 5, 2025
fb04253
feat(browser-sdk): add warning mechanism for missing feature context …
pavkam Feb 5, 2025
f1f77cd
docs(browser-sdk,node-sdk): enhance documentation with new features a…
pavkam Feb 5, 2025
6783288
docs(browser-sdk,node-sdk,react-sdk): improve documentation and forma…
pavkam Feb 5, 2025
b406c13
refactor(browser-sdk,node-sdk,react-sdk): remove default flag from fe…
pavkam Feb 8, 2025
6005cf3
docs(docs-script): enhance markdown processing and hint conversion
pavkam Feb 10, 2025
9f60154
docs(node-sdk): update markdown documentation with GitHub-style block…
pavkam Feb 10, 2025
98e57e3
chore: revert node changes
pavkam Feb 12, 2025
9f72e02
Merge branch 'browser-react-3.0.alpha' into extent-check-events-browser
pavkam Feb 12, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions docs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,46 @@ typedoc
# We can fix this by removing the number at the end of the anchor.
SEDCOMMAND='s/globals.md#(.*)-[0-9]+/globals.md#\1/g'

FILES=$(find dist/docs/@bucketco -name "globals.md")
# Find all markdown files including globals.md
FILES=$(find dist/docs/@bucketco -name "*.md")

echo "Processing markdown files..."
for file in $FILES
do
sed -r $SEDCOMMAND $file > $file.fixed
rm $file
mv $file.fixed $file
echo "Processing $file..."

# Fix anchor links in globals.md files
if [[ "$file" == *"globals.md" ]]; then
sed -r "$SEDCOMMAND" "$file" > "$file.fixed"
rm "$file"
mv "$file.fixed" "$file"
fi

# Create a temporary file for processing
tmp_file="${file}.tmp"

# Process NOTE blocks - handle multi-line
awk '
BEGIN { in_block = 0; content = ""; }
/^> \[!NOTE\]/ { in_block = 1; print "{% hint style=\"info\" %}"; next; }
/^> \[!TIP\]/ { in_block = 1; print "{% hint style=\"success\" %}"; next; }
/^> \[!IMPORTANT\]/ { in_block = 1; print "{% hint style=\"warning\" %}"; next; }
/^> \[!WARNING\]/ { in_block = 1; print "{% hint style=\"warning\" %}"; next; }
/^> \[!CAUTION\]/ { in_block = 1; print "{% hint style=\"danger\" %}"; next; }
in_block && /^>/ {
content = content substr($0, 3) "\n";
next;
}
in_block && !/^>/ {
printf "%s", content;
print "{% endhint %}";
in_block = 0;
content = "";
}
!in_block { print; }
' "$file" > "$tmp_file"

mv "$tmp_file" "$file"
done

echo "Processing complete!"
12 changes: 5 additions & 7 deletions packages/browser-sdk/FEEDBACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ the viewport, displayed in English, and with a [light-mode theme](#custom-stylin

These settings can be overwritten when initializing the Bucket Browser SDK:

```javascript
```typescript
const bucket = new BucketClient({
publishableKey: "bucket-publishable-key",
user: { id: "42" },
Expand All @@ -39,11 +39,9 @@ const bucket = new BucketClient({

See also:

- [Positioning and behavior](#positioning-and-behavior) for the position option.
- [Static language configuration](#static-language-configuration) if you want to
translate the feedback UI.
- [Automated feedback surveys](#automated-feedback-surveys) to
override default configuration.
- [Positioning and behavior](#positioning-and-behavior) for the position option,
- [Static language configuration](#static-language-configuration) if you want to translate the feedback UI,
- [Automated feedback surveys](#automated-feedback-surveys) to override default configuration.

## Automated feedback surveys

Expand All @@ -63,7 +61,7 @@ The live connection for automated feedback is established when the

You can disable automated collection in the `BucketClient` constructor:

```javascript
```typescript
const bucket = new BucketClient({
publishableKey: "bucket-publishable-key",
user: { id: "42" },
Expand Down
99 changes: 69 additions & 30 deletions packages/browser-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ First find your `publishableKey` under [environment settings](https://app.bucket

The package can be imported or used directly in a HTML script tag:

A. Import module
A. Import module:

```ts
```typescript
import { BucketClient } from "@bucketco/browser-sdk";

const user = {
Expand Down Expand Up @@ -93,19 +93,21 @@ See [example/browser.html](https://github.com/bucketco/bucket-javascript-sdk/tre

Supply these to the constructor call:

```ts
```typescript
type Configuration = {
logger: console; // by default only logs warn/error, by passing `console` you'll log everything
apiBaseUrl?: "https://front.bucket.co";
sseBaseUrl?: "https://livemessaging.bucket.co";
feedback?: undefined; // See FEEDBACK.md
enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Bucket servers. Useful when you're impersonating a user.
enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Bucket servers. Useful when you're impersonating a user
featureOptions?: {
fallbackFeatures?: string[]; // Enable these features if unable to contact bucket.co
timeoutMs?: number; // Timeout for fetching features
staleWhileRevalidate?: boolean; // Revalidate in the background when cached features turn stale to avoid latency in the UI
staleTimeMs?: number; // at initialization time features are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase in the case of a non-SPA.
expireTimeMs?: number; // In case we're unable to fetch features from Bucket, cached/stale features will be used instead until they expire after `expireTimeMs`.
fallbackFeatures?:
| string[]
| Record<string, { key: string; payload: any } | true>; // Enable these features if unable to contact bucket.co. Can be a list of feature keys or a record with configuration values
timeoutMs?: number; // Timeout for fetching features (default: 5000ms)
staleWhileRevalidate?: boolean; // Revalidate in the background when cached features turn stale to avoid latency in the UI (default: false)
staleTimeMs?: number; // at initialization time features are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase in the case of a non-SPA
expireTimeMs?: number; // In case we're unable to fetch features from Bucket, cached/stale features will be used instead until they expire after `expireTimeMs`. Default is 30 days
};
};
```
Expand All @@ -120,9 +122,9 @@ In addition to the `id`, you must also supply anything additional that you want
Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans.
Some attributes are special and used in Bucket UI:

- `name` is used to display name for `user`/`company`,
- `email` is accepted for `user`s and will be highlighted in the Bucket UI if available,
- `avatar` can be provided for both `user` and `company` and should be an URL to an image.
- `name` -- display name for `user`/`company`,
- `email` -- is accepted for `user`s and will be highlighted in the Bucket UI if available,
- `avatar` -- can be provided for both `user` and `company` and should be an URL to an image.

```ts
const bucketClient = new BucketClient({
Expand Down Expand Up @@ -172,6 +174,43 @@ by down-stream clients, like the React SDK.
Note that accessing `isEnabled` on the object returned by `getFeatures` does not automatically
generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFeature`.

### Feature Overrides

You can override feature flags locally for testing purposes using `setFeatureOverride`:

```ts
// Override a feature to be enabled
bucketClient.setFeatureOverride("huddle", true);

// Override a feature to be disabled
bucketClient.setFeatureOverride("huddle", false);

// Remove the override
bucketClient.setFeatureOverride("huddle", null);

// Get current override value
const override = bucketClient.getFeatureOverride("huddle"); // returns boolean | null
```

Feature overrides are persisted in `localStorage` and will be restored when the page is reloaded.

### Feature Updates

You can listen for feature updates using `onFeaturesUpdated`:

```ts
// Register a callback for feature updates
const unsubscribe = bucketClient.onFeaturesUpdated(() => {
console.log("Features were updated");
});

// Later, stop listening for updates
unsubscribe();
```

> [!NOTE]
> Note that the callback may be called even if features haven't actually changed.

### Remote config

Similar to `isEnabled`, each feature has a `config` property. This configuration is managed from within Bucket.
Expand Down Expand Up @@ -225,7 +264,7 @@ const { isEnabled } = bucketClient.getFeature("voiceHuddle");
await bucketClient.updateUser({ voiceHuddleOptIn: (!isEnabled).toString() });
```

Note that user/company attributes are also stored remotely on the Bucket servers and will automatically be used to evaluate feature targeting if the page is refreshed.
> [!NOTE] > `user`/`company` attributes are also stored remotely on the Bucket servers and will automatically be used to evaluate feature targeting if the page is refreshed.

### Qualitative feedback

Expand All @@ -235,7 +274,8 @@ Bucket can collect qualitative feedback from your users in the form of a [Custom

The Bucket Browser SDK comes with automated feedback collection mode enabled by default, which lets the Bucket service ask your users for feedback for relevant features just after they've used them.

Note: To get started with automatic feedback collection, make sure you've set `user` in the `BucketClient` constructor.
> [!NOTE]
> To get started with automatic feedback collection, make sure you've set `user` in the `BucketClient` constructor.

Automated feedback surveys work even if you're not using the SDK to send events to Bucket.
It works because the Bucket Browser SDK maintains a live connection to Bucket's servers and can automatically show a feedback prompt whenever the Bucket servers determines that an event should trigger a prompt - regardless of how this event is sent to Bucket.
Expand All @@ -262,7 +302,7 @@ bucketClient.feedback({
});
```

#### Bucket feedback API
### Bucket feedback API

If you are not using the Bucket Browser SDK, you can still submit feedback using the HTTP API.

Expand All @@ -274,9 +314,9 @@ The Bucket Browser SDK doesn't collect any metadata and HTTP IP addresses are _n

For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Bucket, you can hash the sensitive data before sending it to Bucket:

```
```ts
import bucket from "@bucketco/browser-sdk";
import { sha256 } from 'crypto-hash';
import { sha256 } from "crypto-hash";

bucket.user(await sha256("john_doe"));
```
Expand All @@ -290,28 +330,27 @@ The two cookies are:
- `bucket-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys
- `bucket-token-${userId}`: caching a token used to connect to Bucket's live messaging infrastructure that is used to deliver automated feedback surveys in real time.

### Typescript
### TypeScript

Types are bundled together with the library and exposed automatically when importing through a package manager.

## Content Security Policy (CSP)

If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK:

| Directive | Values | Reason |
| ----------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| connect-src | https://front.bucket.co | Basic functionality` |
| connect-src | https://livemessaging.bucket.co | Server sent events for use in automated feedback surveys, which allows for automatically collecting feedback when a user used a feature. |
| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. |
| Directive | Values | Reason |
| ----------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| connect-src | [https://front.bucket.co](https://front.bucket.co) | Basic functionality` |
| connect-src | [https://livemessaging.bucket.co](https://livemessaging.bucket.co) | Server sent events for use in automated feedback surveys, which allows for automatically collecting feedback when a user used a feature. |
| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. |

If you are including the Bucket tracking SDK with a `<script>`-tag from `jsdelivr.net` you will also need:

| Directive | Values | Reason |
| --------------- | ------------------------ | ------------------------------- |
| script-src-elem | https://cdn.jsdelivr.net | Loads the Bucket SDK from a CDN |

# License
| Directive | Values | Reason |
| --------------- | ---------------------------------------------------- | ------------------------------- |
| script-src-elem | [https://cdn.jsdelivr.net](https://cdn.jsdelivr.net) | Loads the Bucket SDK from a CDN |

MIT License
## License

Copyright (c) 2025 Bucket ApS
> MIT License
> Copyright (c) 2025 Bucket ApS
2 changes: 1 addition & 1 deletion packages/browser-sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bucketco/browser-sdk",
"version": "3.0.0-alpha.2",
"version": "3.0.0-alpha.3",
"packageManager": "yarn@4.1.1",
"license": "MIT",
"repository": {
Expand Down
42 changes: 28 additions & 14 deletions packages/browser-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -707,25 +707,39 @@ export class BucketClient {
}
: { key: undefined, payload: undefined };

function sendCheckEvent() {
fClient
.sendCheckEvent({
key,
version: f?.targetingVersion,
value,
})
.catch(() => {
// ignore
});
}

return {
get isEnabled() {
sendCheckEvent();
fClient
.sendCheckEvent({
action: "check",
key,
version: f?.targetingVersion,
ruleEvaluationResults: f?.ruleEvaluationResults,
missingContextFields: f?.missingContextFields,
value,
})
.catch(() => {
// ignore
});
return value;
},
get config() {
sendCheckEvent();
fClient
.sendCheckEvent({
action: "check-config",
key,
version: f?.config?.version,
ruleEvaluationResults: f?.config?.ruleEvaluationResults,
missingContextFields: f?.config?.missingContextFields,
value: f?.config && {
key: f.config.key,
payload: f.config.payload,
},
})
.catch(() => {
// ignore
});

return config;
},
track: () => this.track(key),
Expand Down
8 changes: 7 additions & 1 deletion packages/browser-sdk/src/feature/featureCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ export function parseAPIFeaturesResponse(
typeof feature.isEnabled !== "boolean" ||
feature.key !== key ||
typeof feature.targetingVersion !== "number" ||
(feature.config && typeof feature.config !== "object")
(feature.config && typeof feature.config !== "object") ||
(feature.missingContextFields &&
!Array.isArray(feature.missingContextFields)) ||
(feature.ruleEvaluationResults &&
!Array.isArray(feature.ruleEvaluationResults))
) {
return;
}
Expand All @@ -37,6 +41,8 @@ export function parseAPIFeaturesResponse(
targetingVersion: feature.targetingVersion,
key,
config: feature.config,
missingContextFields: feature.missingContextFields,
ruleEvaluationResults: feature.ruleEvaluationResults,
};
}

Expand Down
Loading