Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/browser-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,11 @@ export interface Config {
* Whether to enable tracking.
*/
enableTracking: boolean;

/**
* Whether to enable offline mode.
*/
offline: boolean;
}

/**
Expand Down Expand Up @@ -228,6 +233,11 @@ export type InitOptions = {
*/
appBaseUrl?: string;

/**
* Whether to enable offline mode. Defaults to `false`.
*/
offline?: boolean;

/**
* Feature keys for which `isEnabled` should fallback to true
* if SDK fails to fetch features from Bucket servers. If a record
Expand Down Expand Up @@ -294,6 +304,7 @@ const defaultConfig: Config = {
appBaseUrl: APP_BASE_URL,
sseBaseUrl: SSE_REALTIME_BASE_URL,
enableTracking: true,
offline: false,
};

/**
Expand Down Expand Up @@ -396,6 +407,7 @@ export class BucketClient {
appBaseUrl: opts?.appBaseUrl ?? defaultConfig.appBaseUrl,
sseBaseUrl: opts?.sseBaseUrl ?? defaultConfig.sseBaseUrl,
enableTracking: opts?.enableTracking ?? defaultConfig.enableTracking,
offline: opts?.offline ?? defaultConfig.offline,
};

this.requestFeedbackOptions = {
Expand Down Expand Up @@ -423,10 +435,12 @@ export class BucketClient {
staleTimeMs: opts.staleTimeMs,
fallbackFeatures: opts.fallbackFeatures,
timeoutMs: opts.timeoutMs,
offline: this.config.offline,
},
);

if (
!this.config.offline &&
this.context?.user &&
!isNode && // do not prompt on server-side
opts?.feedback?.enableAutoFeedback !== false // default to on
Expand Down Expand Up @@ -470,6 +484,7 @@ export class BucketClient {
* Must be called before calling other SDK methods.
*/
async initialize() {
const start = Date.now();
if (this.autoFeedback) {
// do not block on automated feedback surveys initialization
this.autoFeedbackInit = this.autoFeedback.initialize().catch((e) => {
Expand All @@ -489,6 +504,13 @@ export class BucketClient {
this.logger.error("error sending company", e);
});
}

this.logger.info(
"Bucket initialized in " +
Math.round(Date.now() - start) +
"ms" +
(this.config.offline ? " (offline mode)" : ""),
);
}

/**
Expand Down Expand Up @@ -607,6 +629,10 @@ export class BucketClient {
return;
}

if (this.config.offline) {
return;
}

const payload: TrackedEvent = {
userId: String(this.context.user.id),
event: eventName,
Expand Down Expand Up @@ -634,9 +660,14 @@ export class BucketClient {
* @returns The server response.
*/
async feedback(payload: Feedback) {
if (this.config.offline) {
return;
}

const userId =
payload.userId ||
(this.context.user?.id ? String(this.context.user?.id) : undefined);

const companyId =
payload.companyId ||
(this.context.company?.id ? String(this.context.company?.id) : undefined);
Expand Down Expand Up @@ -833,6 +864,10 @@ export class BucketClient {
return;
}

if (this.config.offline) {
return;
}

const { id, ...attributes } = this.context.user;
const payload: User = {
userId: String(id),
Expand Down Expand Up @@ -863,6 +898,10 @@ export class BucketClient {
return;
}

if (this.config.offline) {
return;
}

const { id, ...attributes } = this.context.company;
const payload: Company = {
userId: String(this.context.user.id),
Expand Down
13 changes: 12 additions & 1 deletion packages/browser-sdk/src/feature/features.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,14 @@ type Config = {
fallbackFeatures: Record<string, FallbackFeatureOverride>;
timeoutMs: number;
staleWhileRevalidate: boolean;
offline: boolean;
};

export const DEFAULT_FEATURES_CONFIG: Config = {
fallbackFeatures: {},
timeoutMs: 5000,
staleWhileRevalidate: false,
offline: false,
};

export function validateFeaturesResponse(response: any) {
Expand Down Expand Up @@ -235,6 +237,7 @@ export class FeaturesClient {
expireTimeMs?: number;
cache?: FeatureCache;
rateLimiter?: RateLimiter;
offline?: boolean;
},
) {
this.fetchedFeatures = {};
Expand Down Expand Up @@ -265,7 +268,11 @@ export class FeaturesClient {
fallbackFeatures = options?.fallbackFeatures ?? {};
}

this.config = { ...DEFAULT_FEATURES_CONFIG, ...options, fallbackFeatures };
this.config = {
...DEFAULT_FEATURES_CONFIG,
...options,
fallbackFeatures,
};

this.rateLimiter =
options?.rateLimiter ??
Expand Down Expand Up @@ -456,6 +463,10 @@ export class FeaturesClient {
}

private async maybeFetchFeatures(): Promise<FetchedFeatures | undefined> {
if (this.config.offline) {
return;
}

const cacheKey = this.fetchParams().toString();
const cachedItem = this.cache.get(cacheKey);

Expand Down
25 changes: 25 additions & 0 deletions packages/browser-sdk/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { featuresResult } from "./mocks/handlers";
describe("BucketClient", () => {
let client: BucketClient;
const httpClientPost = vi.spyOn(HttpClient.prototype as any, "post");
const httpClientGet = vi.spyOn(HttpClient.prototype as any, "get");

const featureClientSetContext = vi.spyOn(
FeaturesClient.prototype,
Expand All @@ -21,6 +22,8 @@ describe("BucketClient", () => {
user: { id: "user1" },
company: { id: "company1" },
});

vi.clearAllMocks();
});

describe("updateUser", () => {
Expand Down Expand Up @@ -161,4 +164,26 @@ describe("BucketClient", () => {
expect(featuresUpdated).not.toHaveBeenCalled();
});
});

describe("offline mode", () => {
it("should not make HTTP calls when offline", async () => {
client = new BucketClient({
publishableKey: "test-key",
user: { id: "user1" },
company: { id: "company1" },
offline: true,
feedback: { enableAutoFeedback: true },
});

await client.initialize();
await client.track("offline-event");
await client.feedback({ featureKey: "featureA", score: 5 });
await client.updateUser({ name: "New User" });
await client.updateCompany({ name: "New Company" });
await client.stop();

expect(httpClientPost).not.toHaveBeenCalled();
expect(httpClientGet).not.toHaveBeenCalled();
});
});
});