Skip to content
Open
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
5 changes: 3 additions & 2 deletions packages/react-native/src/lib/common/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,9 @@ export class RNConfig {

// check if the config has expired
if (
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- need to check if expiresAt is set
parsedConfig.workspace.expiresAt &&
// A failed first setup stores only the error status, with no workspace, so both can be missing.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- see above
parsedConfig.workspace?.expiresAt &&
new Date(parsedConfig.workspace.expiresAt) <= new Date()
) {
return err(new Error("Config in local storage has expired"));
Expand Down
2 changes: 1 addition & 1 deletion packages/react-native/src/lib/common/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ const shouldReturnEarlyForErrorState = (
if (existingConfig?.status.value === "error") {
logger.debug("Formbricks was set to an error state.");
const expiresAt = existingConfig.status.expiresAt;
if (expiresAt && isNowExpired(expiresAt)) {
if (expiresAt && !isNowExpired(expiresAt)) {
logger.debug("Error state is not expired, skipping setup");
return true;
}
Expand Down
17 changes: 17 additions & 0 deletions packages/react-native/src/lib/common/tests/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ describe("RNConfig", () => {
}
});

test("loadFromStorage() reads back the error state a failed first setup writes", async () => {
const expiresAt = new Date(Date.now() + 10 * 60000);
// handleErrorOnFirstSetup stores only the status, with no workspace.
vi.spyOn(AsyncStorage, "getItem").mockResolvedValueOnce(
JSON.stringify({ status: { value: "error", expiresAt } }),
);

const result = await configInstance.loadFromStorage();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.data.status).toEqual({
value: "error",
expiresAt: expiresAt.toISOString(),
});
}
});

test("loadFromStorage() migrates legacy { environmentId, environment } shape", async () => {
const { workspaceId, workspace, ...rest } = mockConfig;
const legacyStored = {
Expand Down
116 changes: 76 additions & 40 deletions packages/react-native/src/lib/common/tests/setup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,62 +251,98 @@ describe("setup.ts", () => {
);
});

test("skips setup if existing config is in error state and not expired", async () => {
const mockConfig = {
describe("error state back-off", () => {
const errorConfig = (expiresAt: Date | string) => ({
get: vi.fn().mockReturnValue({
workspaceId: "env_123",
appUrl: "https://my.url",
workspace: {},
user: { data: {}, expiresAt: null },
status: { value: "error", expiresAt: new Date(Date.now() + 10000) },
status: { value: "error", expiresAt },
}),
};
});

getInstanceConfigMock.mockReturnValue(
mockConfig as unknown as Promise<RNConfig>,
);
beforeEach(async () => {
// Exercise the real expiry check instead of pinning a mocked answer.
const actual =
await vi.importActual<typeof CommonUtilsModule>("@/lib/common/utils");
(isNowExpired as unknown as Mock).mockImplementation(
actual.isNowExpired,
);
});

(isNowExpired as unknown as Mock).mockReturnValue(true);
afterEach(() => {
(isNowExpired as unknown as Mock).mockReset();
});

const result = await setup({
environmentId: "env_123",
appUrl: "https://my.url",
test.each([
["a Date", new Date(Date.now() + 5 * 60000)],
// Configs read back from AsyncStorage carry dates as ISO strings.
["an ISO string", new Date(Date.now() + 5 * 60000).toISOString()],
])("skips setup while the error state has not expired (%s)", async (_, expiresAt) => {
getInstanceConfigMock.mockReturnValue(
errorConfig(expiresAt) as unknown as Promise<RNConfig>,
);

const result = await setup({
workspaceId: "env_123",
appUrl: "https://my.url",
});

expect(result.ok).toBe(true);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Formbricks was set to an error state.",
);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Error state is not expired, skipping setup",
);
expect(mockLogger.debug).not.toHaveBeenCalledWith("Start setup");
});
expect(result.ok).toBe(true);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Formbricks was set to an error state.",
);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Error state is not expired, skipping setup",
);
});

test("proceeds if error state is expired", async () => {
const mockConfig = {
get: vi.fn().mockReturnValue({
test.each([
["a Date", new Date(Date.now() - 1000)],
["an ISO string", new Date(Date.now() - 1000).toISOString()],
])("continues setup once the error state has expired (%s)", async (_, expiresAt) => {
getInstanceConfigMock.mockReturnValue(
errorConfig(expiresAt) as unknown as Promise<RNConfig>,
);

const result = await setup({
workspaceId: "env_123",
appUrl: "https://my.url",
workspace: {},
user: { data: {}, expiresAt: null },
status: { value: "error", expiresAt: new Date(Date.now() - 10000) }, // expired
}),
};
});

getInstanceConfigMock.mockReturnValue(
mockConfig as unknown as Promise<RNConfig>,
);
expect(result.ok).toBe(true);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Error state is expired. Continue with setup.",
);
expect(mockLogger.debug).not.toHaveBeenCalledWith(
"Error state is not expired, skipping setup",
);
expect(mockLogger.debug).toHaveBeenCalledWith("Start setup");
});

const result = await setup({
environmentId: "env_123",
appUrl: "https://my.url",
test("skips setup inside the window and continues after it", async () => {
vi.useFakeTimers();
try {
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
getInstanceConfigMock.mockReturnValue(
errorConfig(
new Date("2026-01-01T00:10:00Z"),
) as unknown as Promise<RNConfig>,
);

vi.setSystemTime(new Date("2026-01-01T00:09:59Z"));
await setup({ workspaceId: "env_123", appUrl: "https://my.url" });
expect(mockLogger.debug).not.toHaveBeenCalledWith("Start setup");

vi.setSystemTime(new Date("2026-01-01T00:10:00Z"));
await setup({ workspaceId: "env_123", appUrl: "https://my.url" });
expect(mockLogger.debug).toHaveBeenCalledWith("Start setup");
} finally {
vi.useRealTimers();
}
});
expect(result.ok).toBe(true);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Formbricks was set to an error state.",
);
expect(mockLogger.debug).toHaveBeenCalledWith(
"Error state is expired. Continue with setup.",
);
});

test("uses existing config if workspaceId/appUrl match, checks for expiration sync", async () => {
Expand Down
20 changes: 20 additions & 0 deletions packages/react-native/src/lib/common/tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
getDefaultLanguageCode,
getLanguageCode,
getStyling,
isNowExpired,
shouldDisplayBasedOnPercentage,
wrapThrowsAsync,
} from "@/lib/common/utils";
Expand Down Expand Up @@ -48,6 +49,25 @@ describe("utils.ts", () => {
});
});

// ---------------------------------------------------------------------------------
// isNowExpired
// ---------------------------------------------------------------------------------
describe("isNowExpired()", () => {
test("is false before the expiry and true from it on", () => {
expect(isNowExpired(new Date(Date.now() + 60000))).toBe(false);
expect(isNowExpired(new Date(Date.now() - 1))).toBe(true);
});

test("reads an ISO string, the shape a date has after AsyncStorage", () => {
expect(isNowExpired(new Date(Date.now() + 60000).toISOString())).toBe(
false,
);
expect(isNowExpired(new Date(Date.now() - 60000).toISOString())).toBe(
true,
);
});
});

// ---------------------------------------------------------------------------------
// wrapThrowsAsync
// ---------------------------------------------------------------------------------
Expand Down
6 changes: 4 additions & 2 deletions packages/react-native/src/lib/common/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,10 @@ export const shouldDisplayBasedOnPercentage = (
return Math.random() * 100 < displayPercentage; // NOSONAR: Math.random() is sufficient for non-security survey display logic
};

export const isNowExpired = (expirationDate: Date): boolean => {
return new Date() >= expirationDate;
// A date read back from AsyncStorage is an ISO string, so normalise before comparing:
// `new Date() >= "2026-…"` compares a number with NaN and is always false.
export const isNowExpired = (expirationDate: Date | string): boolean => {
return Date.now() >= new Date(expirationDate).getTime();
};

export const delayedResult = async <T>(value: T, ms: number): Promise<T> => {
Expand Down
Loading