diff --git a/.changeset/auto-feedback-late-user.md b/.changeset/auto-feedback-late-user.md new file mode 100644 index 00000000..1d81ec07 --- /dev/null +++ b/.changeset/auto-feedback-late-user.md @@ -0,0 +1,6 @@ +--- +"@reflag/browser-sdk": patch +"@reflag/openfeature-browser-provider": patch +--- + +Start automatic feedback surveys when a user ID is first set after the client was created without one, for example with `setContext()` or `updateUser()` after sign-in. Previously, surveys only worked if the client was created with a user. The OpenFeature Browser provider now updates its client's context instead of starting a new client when the first user ID arrives. diff --git a/packages/browser-sdk/src/client.ts b/packages/browser-sdk/src/client.ts index 8afccf81..cc5eb707 100644 --- a/packages/browser-sdk/src/client.ts +++ b/packages/browser-sdk/src/client.ts @@ -435,7 +435,8 @@ export class ReflagClient { private requestFeedbackOptions: Partial; private readonly httpClient: HttpClient; - private readonly autoFeedback: AutoFeedback | undefined; + private autoFeedback: AutoFeedback | undefined; + private readonly feedbackOptions: FeedbackOptions | undefined; private autoFeedbackInit: Promise | undefined; private readonly enableLiveFlagUpdates: boolean; private readonly eventSourceFactory: EventSourceFactory | undefined; @@ -573,30 +574,8 @@ export class ReflagClient { }, ); - if ( - !this.config.offline && - this.context?.user && - !isNode && // do not prompt on server-side - opts?.feedback?.enableAutoFeedback !== false // default to on - ) { - if (isMobile) { - this.logger.warn( - "Feedback prompting is not supported on mobile devices", - ); - } else { - this.autoFeedback = new AutoFeedback( - this.config.sseBaseUrl, - this.logger, - this.httpClient, - opts?.feedback?.autoFeedbackHandler, - String(this.context.user?.id), - opts?.feedback?.ui?.position, - opts?.feedback?.ui?.translations, - bulkQueue ? (event) => bulkQueue.enqueue(event) : undefined, - this.credentials, - ); - } - } + this.feedbackOptions = opts?.feedback; + this.autoFeedback = this.createAutoFeedback(); if (shouldShowToolbar(opts)) { const position = @@ -642,7 +621,8 @@ export class ReflagClient { // latest flag-update message, including `flagStateVersion`, so // `reconcileFlagsWithLatestPubSubVersion()` below can catch up if an update // lands between the fetch and the SSE subscription. - if (!this.config.offline && wantsPubSub && hasPubSubTransport) { + // Check again: automatic feedback may have started while flags loaded. + if (!this.config.offline && this.wantsPubSub() && hasPubSubTransport) { // do not block on pubsub initialization this.logger.debug("initializing pubsub"); this.pubSubInit = this.initializePubSub().catch((e) => { @@ -1618,9 +1598,54 @@ export class ReflagClient { } } + /** + * Automatic feedback needs an identified user, so it's created when the + * client starts with one or when the first user ID arrives later. + */ + private createAutoFeedback() { + if ( + this.config.offline || + !hasId(this.context.user?.id) || + isNode || // do not prompt on server-side + this.feedbackOptions?.enableAutoFeedback === false // default to on + ) { + return undefined; + } + if (isMobile) { + this.logger.warn("Feedback prompting is not supported on mobile devices"); + return undefined; + } + const bulkQueue = this.bulkQueue; + return new AutoFeedback( + this.config.sseBaseUrl, + this.logger, + this.httpClient, + this.feedbackOptions?.autoFeedbackHandler, + String(this.context.user!.id), + this.feedbackOptions?.ui?.position, + this.feedbackOptions?.ui?.translations, + bulkQueue ? (event) => bulkQueue.enqueue(event) : undefined, + this.credentials, + ); + } + private async updateAutoFeedbackUser(userId: string) { if (!this.autoFeedback) { - return; + // The client started without a user. Start automatic feedback now. + this.autoFeedback = this.createAutoFeedback(); + if (!this.autoFeedback) return; + // Before initialize(), or after stop(), don't open a connection; + // initialize() opens it. With live updates on, the connection already + // exists and is reopened below. + if (this.state === "idle" || this.state === "stopped") return; + if (!this.pubSubInit) { + if (!this.hasPubSubTransport()) return; + this.pubSubInit = this.initializePubSub().catch((e) => { + this.logger.error("error initializing pubsub", e); + }); + await this.pubSubInit; + return; + } } if (this.pubSubInit) { diff --git a/packages/browser-sdk/test/feedback-context.test.ts b/packages/browser-sdk/test/feedback-context.test.ts index 3c1dee8e..2e775d5b 100644 --- a/packages/browser-sdk/test/feedback-context.test.ts +++ b/packages/browser-sdk/test/feedback-context.test.ts @@ -16,7 +16,13 @@ afterEach(async () => { vi.restoreAllMocks(); }); -function create(userId: string | number) { +function create( + userId: string | number | undefined, + options: { + enableLiveFlagUpdates?: boolean; + enableAutoFeedback?: boolean; + } = {}, +) { const received = vi .spyOn(AutoFeedback.prototype, "handleFeedbackPromptRequest") .mockImplementation(() => undefined); @@ -39,10 +45,12 @@ function create(userId: string | number) { }); const client = new ReflagClient({ publishableKey: "feedback-context", - user: { id: userId }, + user: userId === undefined ? undefined : { id: userId }, enableTracking: false, toolbar: false, eventSourceFactory, + enableLiveFlagUpdates: options.enableLiveFlagUpdates, + feedback: { enableAutoFeedback: options.enableAutoFeedback }, }); clients.push(client); return { client, eventSourceFactory, received }; @@ -92,3 +100,67 @@ test.each(["setContext", "updateUser", "bootstrap"] as const)( expect(received).toHaveBeenCalledWith("0", prompt.data); }, ); + +test.each([false, true])( + "starts automatic feedback when the first user ID arrives (live updates: %s)", + async (enableLiveFlagUpdates) => { + const { client, eventSourceFactory, received } = create(undefined, { + enableLiveFlagUpdates, + }); + await client.initialize(); + expect(eventSourceFactory).toHaveBeenCalledTimes( + enableLiveFlagUpdates ? 1 : 0, + ); + + await client.setContext({ user: { id: "alice" } }); + + const calls = enableLiveFlagUpdates ? 2 : 1; + await vi.waitFor(() => + expect(eventSourceFactory).toHaveBeenCalledTimes(calls), + ); + if (enableLiveFlagUpdates) + expect(eventSourceFactory.mock.results[0].value.close).toHaveBeenCalled(); + const source = eventSourceFactory.mock.results[calls - 1].value; + expect( + JSON.parse(new URL(source.url).searchParams.get("contextJson")!), + ).toMatchObject({ user: { id: "alice" } }); + source.listeners.get("message")!({ data: JSON.stringify(prompt) }); + expect(received).toHaveBeenCalledWith("alice", prompt.data); + }, +); + +test("starts automatic feedback on initialize when the user arrives first", async () => { + const { client, eventSourceFactory } = create(undefined); + await client.setContext({ user: { id: "alice" } }); + expect(eventSourceFactory).not.toHaveBeenCalled(); + + await client.initialize(); + + await vi.waitFor(() => expect(eventSourceFactory).toHaveBeenCalledOnce()); +}); + +test("keeps automatic feedback off when it's disabled", async () => { + const { client, eventSourceFactory } = create(undefined, { + enableAutoFeedback: false, + }); + await client.initialize(); + + await client.setContext({ user: { id: "alice" } }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(eventSourceFactory).not.toHaveBeenCalled(); +}); + +test("doesn't reconnect a stopped client when the first user ID arrives", async () => { + const { client, eventSourceFactory } = create(undefined, { + enableLiveFlagUpdates: true, + }); + await client.initialize(); + expect(eventSourceFactory).toHaveBeenCalledOnce(); + await client.stop(); + + await client.setContext({ user: { id: "alice" } }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(eventSourceFactory).toHaveBeenCalledOnce(); +}); diff --git a/packages/openfeature-browser-provider/src/index.test.ts b/packages/openfeature-browser-provider/src/index.test.ts index dbbecc84..f08a41d3 100644 --- a/packages/openfeature-browser-provider/src/index.test.ts +++ b/packages/openfeature-browser-provider/src/index.test.ts @@ -26,7 +26,6 @@ describe("ReflagBrowserSDKProvider", () => { getFlagResults: vi.fn(), getFlag: vi.fn(), setContext: vi.fn().mockResolvedValue(undefined), - getContext: vi.fn().mockReturnValue({ user: { id: "user-1" } }), initialize: vi.fn().mockResolvedValue({}), track: vi.fn(), stop: vi.fn(), @@ -98,27 +97,6 @@ describe("ReflagBrowserSDKProvider", () => { ); }); - it("onContextChange drops bootstrapped data when the first user ID arrives", async () => { - const bootstrappedState = { - protocolVersion: 2 as const, - context: {}, - flags: {}, - }; - const p = new ReflagBrowserSDKProvider({ - publishableKey, - bootstrappedState, - }); - await p.initialize(); - reflagClientMock.getContext.mockReturnValueOnce({}); - vi.clearAllMocks(); - - await p.onContextChange({}, { targetingKey: "user-2" }); - expect(mockReflagClient).toHaveBeenCalledWith({ - publishableKey, - ...defaultContextTranslator({ targetingKey: "user-2" }), - }); - }); - it("onContextChange keeps context from the provider options", async () => { const p = new ReflagBrowserSDKProvider({ publishableKey, @@ -133,21 +111,6 @@ describe("ReflagBrowserSDKProvider", () => { ...defaultContextTranslator({ targetingKey: "user-2" }), }); }); - - it("onContextChange starts a new client when the first user ID arrives", async () => { - await provider.initialize(); - reflagClientMock.getContext.mockReturnValueOnce({}); - vi.clearAllMocks(); - - await provider.onContextChange({}, { targetingKey: "user-2" }); - expect(reflagClientMock.stop).toHaveBeenCalledTimes(1); - expect(mockReflagClient).toHaveBeenCalledWith({ - publishableKey, - ...defaultContextTranslator({ targetingKey: "user-2" }), - }); - expect(reflagClientMock.setContext).not.toHaveBeenCalled(); - expect(provider.status).toBe("READY"); - }); }); describe("contextTranslator", () => { diff --git a/packages/openfeature-browser-provider/src/index.ts b/packages/openfeature-browser-provider/src/index.ts index c1d51e42..ef5a9cce 100644 --- a/packages/openfeature-browser-provider/src/index.ts +++ b/packages/openfeature-browser-provider/src/index.ts @@ -22,10 +22,6 @@ function jsonType(value: JsonValue): string { } // A `null` default accepts any JSON value, as in the Reflag SDKs. -function hasId(id: unknown) { - return id !== undefined && id !== null && id !== ""; -} - function isTypeMismatch(value: JsonValue, defaultValue: JsonValue) { return defaultValue !== null && jsonType(value) !== jsonType(defaultValue); } @@ -90,15 +86,8 @@ export class ReflagBrowserSDKProvider implements Provider { } async initialize(context?: EvaluationContext): Promise { - await this.startClient(this._clientOptions, context); - } - - private async startClient( - options: InitOptions, - context?: EvaluationContext, - ): Promise { const client = new ReflagClient({ - ...options, + ...this._clientOptions, ...this._contextTranslator(context), }); @@ -132,23 +121,11 @@ export class ReflagBrowserSDKProvider implements Provider { otherContext, ...this._contextTranslator(newContext), }; - const client = this._client; - if (!client) { + if (!this._client) { await this.initialize(newContext); return; } - // The Browser SDK sets up automatic feedback only when the client starts - // with a user, so start a new client when the first user ID arrives. - if (!hasId(client.getContext().user?.id) && hasId(context.user?.id)) { - this._client = undefined; - await client.stop(); - // Bootstrapped data belongs to the anonymous context, and the SDK would - // prefer its context and skip fetching, so start without it. - const { bootstrappedState: _bootstrap, ...options } = this._clientOptions; - await this.startClient(options, newContext); - return; - } - await client.setContext(context); + await this._client.setContext(context); } private resolveFlag(