mirror of
https://github.com/formbricks/formbricks.git
synced 2026-05-09 11:10:36 -05:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10fe8c1a0c | |||
| 73bee547ee | |||
| a1a11b2bb8 | |||
| 0653c6a59f | |||
| b6d793e109 | |||
| 439dd0b44e | |||
| 2556f5e15d | |||
| cc0eec3bf0 | |||
| 4b009a8eb4 | |||
| 2aaddf7306 | |||
| fb5d6145d0 | |||
| 59310bac93 |
+8
-11
@@ -3,25 +3,22 @@
|
||||
import { InboxIcon, PresentationIcon } from "lucide-react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { useEnvironment } from "@/app/(app)/environments/[environmentId]/context/environment-context";
|
||||
import { revalidateSurveyIdPath } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/actions";
|
||||
import { useSurvey } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/context/survey-context";
|
||||
import { SecondaryNavigation } from "@/modules/ui/components/secondary-navigation";
|
||||
|
||||
interface SurveyAnalysisNavigationProps {
|
||||
environmentId: string;
|
||||
survey: TSurvey;
|
||||
activeId: string;
|
||||
}
|
||||
|
||||
export const SurveyAnalysisNavigation = ({
|
||||
environmentId,
|
||||
survey,
|
||||
activeId,
|
||||
}: SurveyAnalysisNavigationProps) => {
|
||||
export const SurveyAnalysisNavigation = ({ activeId }: SurveyAnalysisNavigationProps) => {
|
||||
const pathname = usePathname();
|
||||
const { t } = useTranslation();
|
||||
const { environment } = useEnvironment();
|
||||
const { survey } = useSurvey();
|
||||
|
||||
const url = `/environments/${environmentId}/surveys/${survey.id}`;
|
||||
const url = `/environments/${environment.id}/surveys/${survey.id}`;
|
||||
|
||||
const navigation = [
|
||||
{
|
||||
@@ -31,7 +28,7 @@ export const SurveyAnalysisNavigation = ({
|
||||
href: `${url}/summary?referer=true`,
|
||||
current: pathname?.includes("/summary"),
|
||||
onClick: () => {
|
||||
revalidateSurveyIdPath(environmentId, survey.id);
|
||||
revalidateSurveyIdPath(environment.id, survey.id);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -41,7 +38,7 @@ export const SurveyAnalysisNavigation = ({
|
||||
href: `${url}/responses?referer=true`,
|
||||
current: pathname?.includes("/responses"),
|
||||
onClick: () => {
|
||||
revalidateSurveyIdPath(environmentId, survey.id);
|
||||
revalidateSurveyIdPath(environment.id, survey.id);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
import { SkeletonLoader } from "@/modules/ui/components/skeleton-loader";
|
||||
|
||||
const Loading = () => {
|
||||
return (
|
||||
<PageContentWrapper>
|
||||
<PageHeader pageTitle="" />
|
||||
<div className="flex h-9 animate-pulse gap-2">
|
||||
<div className="h-9 w-36 rounded-full bg-slate-200" />
|
||||
<div className="h-9 w-36 rounded-full bg-slate-200" />
|
||||
<div className="h-9 w-36 rounded-full bg-slate-200" />
|
||||
<div className="h-9 w-36 rounded-full bg-slate-200" />
|
||||
</div>
|
||||
<SkeletonLoader type="summary" />
|
||||
</PageContentWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export default Loading;
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PageContentWrapper } from "@/modules/ui/components/page-content-wrapper";
|
||||
import { PageHeader } from "@/modules/ui/components/page-header";
|
||||
import { SkeletonLoader } from "@/modules/ui/components/skeleton-loader";
|
||||
|
||||
const Loading = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<PageContentWrapper>
|
||||
<PageHeader pageTitle={t("common.responses")} />
|
||||
<div className="flex h-9 animate-pulse gap-1.5">
|
||||
<div className="h-9 w-36 rounded-full bg-slate-200" />
|
||||
<div className="h-9 w-36 rounded-full bg-slate-200" />
|
||||
</div>
|
||||
<SkeletonLoader type="responseTable" />
|
||||
</PageContentWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export default Loading;
|
||||
+1
-3
@@ -64,8 +64,6 @@ const Page = async (props: { params: Promise<{ environmentId: string; surveyId:
|
||||
pageTitle={survey.name}
|
||||
cta={
|
||||
<SurveyAnalysisCTA
|
||||
environment={environment}
|
||||
survey={survey}
|
||||
isReadOnly={isReadOnly}
|
||||
user={user}
|
||||
publicDomain={publicDomain}
|
||||
@@ -76,7 +74,7 @@ const Page = async (props: { params: Promise<{ environmentId: string; surveyId:
|
||||
isStorageConfigured={IS_STORAGE_CONFIGURED}
|
||||
/>
|
||||
}>
|
||||
<SurveyAnalysisNavigation environmentId={environment.id} survey={survey} activeId="responses" />
|
||||
<SurveyAnalysisNavigation activeId="responses" />
|
||||
</PageHeader>
|
||||
<ResponsePage
|
||||
environment={environment}
|
||||
|
||||
+5
-8
@@ -4,16 +4,13 @@ import { useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TEnvironment } from "@formbricks/types/environment";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { useEnvironment } from "@/app/(app)/environments/[environmentId]/context/environment-context";
|
||||
import { useSurvey } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/context/survey-context";
|
||||
import { Confetti } from "@/modules/ui/components/confetti";
|
||||
|
||||
interface SummaryMetadataProps {
|
||||
environment: TEnvironment;
|
||||
survey: TSurvey;
|
||||
}
|
||||
|
||||
export const SuccessMessage = ({ environment, survey }: SummaryMetadataProps) => {
|
||||
export const SuccessMessage = () => {
|
||||
const { environment } = useEnvironment();
|
||||
const { survey } = useSurvey();
|
||||
const { t } = useTranslation();
|
||||
const searchParams = useSearchParams();
|
||||
const [confetti, setConfetti] = useState(false);
|
||||
|
||||
+5
-9
@@ -5,14 +5,13 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TEnvironment } from "@formbricks/types/environment";
|
||||
import { TSegment } from "@formbricks/types/segment";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { TUser } from "@formbricks/types/user";
|
||||
import { useEnvironment } from "@/app/(app)/environments/[environmentId]/context/environment-context";
|
||||
import { SuccessMessage } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/SuccessMessage";
|
||||
import { ShareSurveyModal } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/(analysis)/summary/components/share-survey-modal";
|
||||
import { SurveyStatusDropdown } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/components/SurveyStatusDropdown";
|
||||
import { useSurvey } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/context/survey-context";
|
||||
import { getFormattedErrorMessage } from "@/lib/utils/helper";
|
||||
import { EditPublicSurveyAlertDialog } from "@/modules/survey/components/edit-public-survey-alert-dialog";
|
||||
import { useSingleUseId } from "@/modules/survey/hooks/useSingleUseId";
|
||||
@@ -23,8 +22,6 @@ import { IconBar } from "@/modules/ui/components/iconbar";
|
||||
import { resetSurveyAction } from "../actions";
|
||||
|
||||
interface SurveyAnalysisCTAProps {
|
||||
survey: TSurvey;
|
||||
environment: TEnvironment;
|
||||
isReadOnly: boolean;
|
||||
user: TUser;
|
||||
publicDomain: string;
|
||||
@@ -41,8 +38,6 @@ interface ModalState {
|
||||
}
|
||||
|
||||
export const SurveyAnalysisCTA = ({
|
||||
survey,
|
||||
environment,
|
||||
isReadOnly,
|
||||
user,
|
||||
publicDomain,
|
||||
@@ -64,7 +59,8 @@ export const SurveyAnalysisCTA = ({
|
||||
const [isResetModalOpen, setIsResetModalOpen] = useState(false);
|
||||
const [isResetting, setIsResetting] = useState(false);
|
||||
|
||||
const { project } = useEnvironment();
|
||||
const { environment, project } = useEnvironment();
|
||||
const { survey } = useSurvey();
|
||||
const { refreshSingleUseId } = useSingleUseId(survey, isReadOnly);
|
||||
|
||||
const appSetupCompleted = survey.type === "app" && environment.appSetupCompleted;
|
||||
@@ -183,7 +179,7 @@ export const SurveyAnalysisCTA = ({
|
||||
return (
|
||||
<div className="hidden justify-end gap-x-1.5 sm:flex">
|
||||
{!isReadOnly && (appSetupCompleted || survey.type === "link") && survey.status !== "draft" && (
|
||||
<SurveyStatusDropdown environment={environment} survey={survey} />
|
||||
<SurveyStatusDropdown />
|
||||
)}
|
||||
|
||||
<IconBar actions={iconActions} />
|
||||
@@ -215,7 +211,7 @@ export const SurveyAnalysisCTA = ({
|
||||
projectCustomScripts={project.customHeadScripts}
|
||||
/>
|
||||
)}
|
||||
<SuccessMessage environment={environment} survey={survey} />
|
||||
<SuccessMessage />
|
||||
|
||||
{responseCount > 0 && (
|
||||
<EditPublicSurveyAlertDialog
|
||||
|
||||
+55
@@ -191,6 +191,61 @@ describe("getSurveySummaryMeta", () => {
|
||||
expect(meta.dropOffPercentage).toBe(0);
|
||||
expect(meta.ttcAverage).toBe(0);
|
||||
});
|
||||
|
||||
test("uses block-level TTC to avoid multiplying by number of elements", () => {
|
||||
const surveyWithOneBlockThreeElements: TSurvey = {
|
||||
...mockBaseSurvey,
|
||||
blocks: [
|
||||
{
|
||||
id: "block1",
|
||||
name: "Block 1",
|
||||
elements: [
|
||||
{
|
||||
id: "q1",
|
||||
type: TSurveyElementTypeEnum.OpenText,
|
||||
headline: { default: "Q1" },
|
||||
required: false,
|
||||
inputType: "text",
|
||||
charLimit: { enabled: false },
|
||||
},
|
||||
{
|
||||
id: "q2",
|
||||
type: TSurveyElementTypeEnum.OpenText,
|
||||
headline: { default: "Q2" },
|
||||
required: false,
|
||||
inputType: "text",
|
||||
charLimit: { enabled: false },
|
||||
},
|
||||
{
|
||||
id: "q3",
|
||||
type: TSurveyElementTypeEnum.OpenText,
|
||||
headline: { default: "Q3" },
|
||||
required: false,
|
||||
inputType: "text",
|
||||
charLimit: { enabled: false },
|
||||
},
|
||||
] as TSurveyElement[],
|
||||
},
|
||||
],
|
||||
questions: [],
|
||||
};
|
||||
|
||||
const responses = [
|
||||
{
|
||||
id: "r1",
|
||||
data: { q1: "a", q2: "b", q3: "c" },
|
||||
updatedAt: new Date(),
|
||||
contact: null,
|
||||
contactAttributes: {},
|
||||
language: "en",
|
||||
ttc: { q1: 5000, q2: 5000, q3: 4800, _total: 14800 },
|
||||
finished: true,
|
||||
},
|
||||
] as any;
|
||||
|
||||
const meta = getSurveySummaryMeta(surveyWithOneBlockThreeElements, responses, 1, mockQuotas);
|
||||
expect(meta.ttcAverage).toBe(5000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSurveySummaryDropOff", () => {
|
||||
|
||||
+7
-1
@@ -1094,7 +1094,9 @@ export const getResponsesForSummary = reactCache(
|
||||
const transformedResponses: TSurveySummaryResponse[] = await Promise.all(
|
||||
responses.map((responsePrisma) => {
|
||||
return {
|
||||
...responsePrisma,
|
||||
id: responsePrisma.id,
|
||||
data: (responsePrisma.data ?? {}) as TResponseData,
|
||||
updatedAt: responsePrisma.updatedAt,
|
||||
contact: responsePrisma.contact
|
||||
? {
|
||||
id: responsePrisma.contact.id as string,
|
||||
@@ -1103,6 +1105,10 @@ export const getResponsesForSummary = reactCache(
|
||||
)?.value as string,
|
||||
}
|
||||
: null,
|
||||
contactAttributes: (responsePrisma.contactAttributes ?? {}) as TResponseContactAttributes,
|
||||
language: responsePrisma.language,
|
||||
ttc: (responsePrisma.ttc ?? {}) as TResponseTtc,
|
||||
finished: responsePrisma.finished,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
+1
-3
@@ -66,8 +66,6 @@ const SurveyPage = async (props: { params: Promise<{ environmentId: string; surv
|
||||
pageTitle={survey.name}
|
||||
cta={
|
||||
<SurveyAnalysisCTA
|
||||
environment={environment}
|
||||
survey={survey}
|
||||
isReadOnly={isReadOnly}
|
||||
user={user}
|
||||
publicDomain={publicDomain}
|
||||
@@ -78,7 +76,7 @@ const SurveyPage = async (props: { params: Promise<{ environmentId: string; surv
|
||||
isStorageConfigured={IS_STORAGE_CONFIGURED}
|
||||
/>
|
||||
}>
|
||||
<SurveyAnalysisNavigation environmentId={environment.id} survey={survey} activeId="summary" />
|
||||
<SurveyAnalysisNavigation activeId="summary" />
|
||||
</PageHeader>
|
||||
<SummaryPage
|
||||
environment={environment}
|
||||
|
||||
+5
-16
@@ -3,8 +3,9 @@
|
||||
import { useRouter } from "next/navigation";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TEnvironment } from "@formbricks/types/environment";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
import { useEnvironment } from "@/app/(app)/environments/[environmentId]/context/environment-context";
|
||||
import { useSurvey } from "@/app/(app)/environments/[environmentId]/surveys/[surveyId]/context/survey-context";
|
||||
import { getFormattedErrorMessage } from "@/lib/utils/helper";
|
||||
import { updateSurveyAction } from "@/modules/survey/editor/actions";
|
||||
import {
|
||||
@@ -16,17 +17,9 @@ import {
|
||||
} from "@/modules/ui/components/select";
|
||||
import { SurveyStatusIndicator } from "@/modules/ui/components/survey-status-indicator";
|
||||
|
||||
interface SurveyStatusDropdownProps {
|
||||
environment: TEnvironment;
|
||||
updateLocalSurveyStatus?: (status: TSurvey["status"]) => void;
|
||||
survey: TSurvey;
|
||||
}
|
||||
|
||||
export const SurveyStatusDropdown = ({
|
||||
environment,
|
||||
updateLocalSurveyStatus,
|
||||
survey,
|
||||
}: SurveyStatusDropdownProps) => {
|
||||
export const SurveyStatusDropdown = () => {
|
||||
const { environment } = useEnvironment();
|
||||
const { survey } = useSurvey();
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
|
||||
@@ -46,10 +39,6 @@ export const SurveyStatusDropdown = ({
|
||||
toast.success(toastMessage);
|
||||
}
|
||||
|
||||
if (updateLocalSurveyStatus) {
|
||||
updateLocalSurveyStatus(resultingStatus);
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
} else {
|
||||
const errorMessage = getFormattedErrorMessage(updateSurveyActionResponse);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { captureSurveyResponsePostHogEvent } from "./posthog";
|
||||
|
||||
vi.mock("@/lib/posthog", () => ({
|
||||
capturePostHogEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("captureSurveyResponsePostHogEvent", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const makeParams = (responseCount: number) => ({
|
||||
organizationId: "org-1",
|
||||
surveyId: "survey-1",
|
||||
surveyType: "link",
|
||||
environmentId: "env-1",
|
||||
responseCount,
|
||||
});
|
||||
|
||||
test("fires on 1st response with milestone 'first'", async () => {
|
||||
const { capturePostHogEvent } = await import("@/lib/posthog");
|
||||
|
||||
captureSurveyResponsePostHogEvent(makeParams(1));
|
||||
|
||||
expect(capturePostHogEvent).toHaveBeenCalledWith("org-1", "survey_response_received", {
|
||||
survey_id: "survey-1",
|
||||
survey_type: "link",
|
||||
organization_id: "org-1",
|
||||
environment_id: "env-1",
|
||||
response_count: 1,
|
||||
is_first_response: true,
|
||||
milestone: "first",
|
||||
});
|
||||
});
|
||||
|
||||
test("fires on every 100th response", async () => {
|
||||
const { capturePostHogEvent } = await import("@/lib/posthog");
|
||||
|
||||
for (const count of [100, 200, 300, 500, 1000, 5000]) {
|
||||
captureSurveyResponsePostHogEvent(makeParams(count));
|
||||
}
|
||||
|
||||
expect(capturePostHogEvent).toHaveBeenCalledTimes(6);
|
||||
});
|
||||
|
||||
test("does NOT fire for 2nd through 99th responses", async () => {
|
||||
const { capturePostHogEvent } = await import("@/lib/posthog");
|
||||
|
||||
for (const count of [2, 5, 10, 50, 99]) {
|
||||
captureSurveyResponsePostHogEvent(makeParams(count));
|
||||
}
|
||||
|
||||
expect(capturePostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("does NOT fire for non-100th counts above 100", async () => {
|
||||
const { capturePostHogEvent } = await import("@/lib/posthog");
|
||||
|
||||
for (const count of [101, 150, 250, 499, 501]) {
|
||||
captureSurveyResponsePostHogEvent(makeParams(count));
|
||||
}
|
||||
|
||||
expect(capturePostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("sets milestone to count string for non-first milestones", async () => {
|
||||
const { capturePostHogEvent } = await import("@/lib/posthog");
|
||||
|
||||
captureSurveyResponsePostHogEvent(makeParams(200));
|
||||
|
||||
expect(capturePostHogEvent).toHaveBeenCalledWith(
|
||||
"org-1",
|
||||
"survey_response_received",
|
||||
expect.objectContaining({
|
||||
is_first_response: false,
|
||||
milestone: "200",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { prisma } from "@formbricks/database";
|
||||
import { ZId } from "@formbricks/types/common";
|
||||
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { validateInputs } from "@/lib/utils/validate";
|
||||
|
||||
export const getResponseIdByDisplayId = async (
|
||||
environmentId: string,
|
||||
displayId: string
|
||||
): Promise<{ responseId: string | null }> => {
|
||||
validateInputs([environmentId, ZId], [displayId, ZId]);
|
||||
|
||||
try {
|
||||
const display = await prisma.display.findFirst({
|
||||
where: {
|
||||
id: displayId,
|
||||
survey: {
|
||||
environmentId,
|
||||
},
|
||||
},
|
||||
select: {
|
||||
response: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!display) {
|
||||
throw new ResourceNotFoundError("Display", displayId);
|
||||
}
|
||||
|
||||
return {
|
||||
responseId: display.response?.id ?? null,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
throw new DatabaseError(error.message);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -1,40 +0,0 @@
|
||||
import { logger } from "@formbricks/logger";
|
||||
import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { responses } from "@/app/lib/api/response";
|
||||
import { THandlerParams, withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { getResponseIdByDisplayId } from "./lib/response";
|
||||
|
||||
export const OPTIONS = async (): Promise<Response> => {
|
||||
return responses.successResponse({}, true);
|
||||
};
|
||||
|
||||
export const GET = withV1ApiWrapper({
|
||||
handler: async ({
|
||||
req,
|
||||
props,
|
||||
}: THandlerParams<{ params: Promise<{ environmentId: string; displayId: string }> }>) => {
|
||||
const params = await props.params;
|
||||
|
||||
try {
|
||||
const response = await getResponseIdByDisplayId(params.environmentId, params.displayId);
|
||||
|
||||
return {
|
||||
response: responses.successResponse(response, true),
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof ResourceNotFoundError) {
|
||||
return {
|
||||
response: responses.notFoundResponse("Display", params.displayId, true),
|
||||
};
|
||||
}
|
||||
|
||||
logger.error(
|
||||
{ error, url: req.url, environmentId: params.environmentId, displayId: params.displayId },
|
||||
"Error in GET /api/v1/client/[environmentId]/displays/[displayId]/response"
|
||||
);
|
||||
return {
|
||||
response: responses.internalServerErrorResponse("Something went wrong. Please try again."),
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -70,6 +70,7 @@ const mockEnvironmentData = {
|
||||
displayOption: "displayOnce",
|
||||
hiddenFields: { enabled: false },
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: true,
|
||||
triggers: [],
|
||||
displayPercentage: null,
|
||||
delay: 0,
|
||||
@@ -122,6 +123,13 @@ describe("getEnvironmentStateData", () => {
|
||||
surveys: expect.any(Object),
|
||||
}),
|
||||
});
|
||||
|
||||
const prismaCall = vi.mocked(prisma.environment.findUnique).mock.calls[0][0];
|
||||
expect(prismaCall.select.surveys.select).toEqual(
|
||||
expect.objectContaining({
|
||||
isAutoProgressingEnabled: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("should throw ResourceNotFoundError when environment is not found", async () => {
|
||||
|
||||
@@ -121,6 +121,7 @@ export const getEnvironmentStateData = async (environmentId: string): Promise<En
|
||||
displayOption: true,
|
||||
hiddenFields: true,
|
||||
isBackButtonHidden: true,
|
||||
isAutoProgressingEnabled: true,
|
||||
triggers: {
|
||||
select: {
|
||||
actionClass: {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Prisma } from "@prisma/client";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { prisma } from "@formbricks/database";
|
||||
import { TContactAttributes } from "@formbricks/types/contact-attribute";
|
||||
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { DatabaseError, ResourceNotFoundError, UniqueConstraintError } from "@formbricks/types/errors";
|
||||
import { TResponseWithQuotaFull, TSurveyQuota } from "@formbricks/types/quota";
|
||||
import { TResponse } from "@formbricks/types/responses";
|
||||
import { TTag } from "@formbricks/types/tags";
|
||||
@@ -175,10 +175,34 @@ describe("createResponse V2", () => {
|
||||
).rejects.toThrow(ResourceNotFoundError);
|
||||
});
|
||||
|
||||
test("should throw DatabaseError on Prisma known request error", async () => {
|
||||
const prismaError = new Prisma.PrismaClientKnownRequestError("Test Prisma Error", {
|
||||
test("should throw UniqueConstraintError on P2002 with singleUseId target", async () => {
|
||||
const prismaError = new Prisma.PrismaClientKnownRequestError("Unique constraint failed", {
|
||||
code: "P2002",
|
||||
clientVersion: "test",
|
||||
meta: { target: ["surveyId", "singleUseId"] },
|
||||
});
|
||||
vi.mocked(mockTx.response.create).mockRejectedValue(prismaError);
|
||||
await expect(
|
||||
createResponse(mockResponseInput, mockTx as unknown as Prisma.TransactionClient)
|
||||
).rejects.toThrow(UniqueConstraintError);
|
||||
});
|
||||
|
||||
test("should throw DatabaseError on P2002 without singleUseId target", async () => {
|
||||
const prismaError = new Prisma.PrismaClientKnownRequestError("Unique constraint failed", {
|
||||
code: "P2002",
|
||||
clientVersion: "test",
|
||||
meta: { target: ["displayId"] },
|
||||
});
|
||||
vi.mocked(mockTx.response.create).mockRejectedValue(prismaError);
|
||||
await expect(
|
||||
createResponse(mockResponseInput, mockTx as unknown as Prisma.TransactionClient)
|
||||
).rejects.toThrow(DatabaseError);
|
||||
});
|
||||
|
||||
test("should throw DatabaseError on non-P2002 Prisma known request error", async () => {
|
||||
const prismaError = new Prisma.PrismaClientKnownRequestError("Test Prisma Error", {
|
||||
code: "P2025",
|
||||
clientVersion: "test",
|
||||
});
|
||||
vi.mocked(mockTx.response.create).mockRejectedValue(prismaError);
|
||||
await expect(
|
||||
|
||||
@@ -2,7 +2,7 @@ import "server-only";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { prisma } from "@formbricks/database";
|
||||
import { TContactAttributes } from "@formbricks/types/contact-attribute";
|
||||
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { DatabaseError, ResourceNotFoundError, UniqueConstraintError } from "@formbricks/types/errors";
|
||||
import { TResponseWithQuotaFull } from "@formbricks/types/quota";
|
||||
import { TResponse, ZResponseInput } from "@formbricks/types/responses";
|
||||
import { TTag } from "@formbricks/types/tags";
|
||||
@@ -129,6 +129,13 @@ export const createResponse = async (
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (error.code === "P2002") {
|
||||
const target = (error.meta?.target as string[]) ?? [];
|
||||
if (target?.includes("singleUseId")) {
|
||||
throw new UniqueConstraintError("Response already submitted for this single-use link");
|
||||
}
|
||||
}
|
||||
|
||||
throw new DatabaseError(error.message);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { UAParser } from "ua-parser-js";
|
||||
import { ZEnvironmentId } from "@formbricks/types/environment";
|
||||
import { InvalidInputError } from "@formbricks/types/errors";
|
||||
import { InvalidInputError, UniqueConstraintError } from "@formbricks/types/errors";
|
||||
import { TResponseWithQuotaFull } from "@formbricks/types/quota";
|
||||
import { checkSurveyValidity } from "@/app/api/v2/client/[environmentId]/responses/lib/utils";
|
||||
import { reportApiError } from "@/app/lib/api/api-error-reporter";
|
||||
@@ -177,6 +177,10 @@ const createResponseForRequest = async ({
|
||||
return responses.badRequestResponse(error.message, undefined, true);
|
||||
}
|
||||
|
||||
if (error instanceof UniqueConstraintError) {
|
||||
return responses.conflictResponse(error.message, undefined, true);
|
||||
}
|
||||
|
||||
const response = getUnexpectedPublicErrorResponse();
|
||||
reportApiError({
|
||||
request,
|
||||
|
||||
@@ -339,6 +339,56 @@ describe("API Response Utilities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("conflictResponse", () => {
|
||||
test("should return a conflict response", () => {
|
||||
const message = "Resource already exists";
|
||||
const details = { field: "singleUseId" };
|
||||
const response = responses.conflictResponse(message, details);
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
|
||||
return response.json().then((body) => {
|
||||
expect(body).toEqual({
|
||||
code: "conflict",
|
||||
message,
|
||||
details,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle undefined details", () => {
|
||||
const message = "Resource already exists";
|
||||
const response = responses.conflictResponse(message);
|
||||
|
||||
expect(response.status).toBe(409);
|
||||
|
||||
return response.json().then((body) => {
|
||||
expect(body).toEqual({
|
||||
code: "conflict",
|
||||
message,
|
||||
details: {},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("should include CORS headers when cors is true", () => {
|
||||
const message = "Resource already exists";
|
||||
const response = responses.conflictResponse(message, undefined, true);
|
||||
|
||||
expect(response.headers.get("Access-Control-Allow-Origin")).toBe("*");
|
||||
expect(response.headers.get("Access-Control-Allow-Methods")).toBe("GET, POST, PUT, DELETE, OPTIONS");
|
||||
expect(response.headers.get("Access-Control-Allow-Headers")).toBe("Content-Type, Authorization");
|
||||
});
|
||||
|
||||
test("should use custom cache control header when provided", () => {
|
||||
const message = "Resource already exists";
|
||||
const customCache = "no-cache";
|
||||
const response = responses.conflictResponse(message, undefined, false, customCache);
|
||||
|
||||
expect(response.headers.get("Cache-Control")).toBe(customCache);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tooManyRequestsResponse", () => {
|
||||
test("should return a too many requests response", () => {
|
||||
const message = "Rate limit exceeded";
|
||||
|
||||
@@ -16,7 +16,8 @@ interface ApiErrorResponse {
|
||||
| "method_not_allowed"
|
||||
| "not_authenticated"
|
||||
| "forbidden"
|
||||
| "too_many_requests";
|
||||
| "too_many_requests"
|
||||
| "conflict";
|
||||
message: string;
|
||||
details: {
|
||||
[key: string]: string | string[] | number | number[] | boolean | boolean[];
|
||||
@@ -236,6 +237,30 @@ const internalServerErrorResponse = (
|
||||
);
|
||||
};
|
||||
|
||||
const conflictResponse = (
|
||||
message: string,
|
||||
details?: { [key: string]: string },
|
||||
cors: boolean = false,
|
||||
cache: string = "private, no-store"
|
||||
) => {
|
||||
const headers = {
|
||||
...(cors && corsHeaders),
|
||||
"Cache-Control": cache,
|
||||
};
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
code: "conflict",
|
||||
message,
|
||||
details: details || {},
|
||||
} as ApiErrorResponse,
|
||||
{
|
||||
status: 409,
|
||||
headers,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const tooManyRequestsResponse = (
|
||||
message: string,
|
||||
cors: boolean = false,
|
||||
@@ -270,4 +295,5 @@ export const responses = {
|
||||
successResponse,
|
||||
tooManyRequestsResponse,
|
||||
forbiddenResponse,
|
||||
conflictResponse,
|
||||
};
|
||||
|
||||
@@ -4926,6 +4926,7 @@ export const previewSurvey = (projectName: string, t: TFunction): TSurvey => {
|
||||
showLanguageSwitch: false,
|
||||
followUps: [],
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: true,
|
||||
isCaptureIpEnabled: false,
|
||||
metadata: {},
|
||||
questions: [], // Required for build-time type checking (Zod defaults to [] at runtime)
|
||||
|
||||
@@ -1288,6 +1288,8 @@ checksums:
|
||||
environments/surveys/edit/assign: e80715ab64bf7cf463abb3a9fd1ad516
|
||||
environments/surveys/edit/audience: a4d9fab4214a641e2d358fbb28f010e0
|
||||
environments/surveys/edit/auto_close_on_inactivity: 093db516799315ccd4242a3675693012
|
||||
environments/surveys/edit/auto_progress_rating_and_nps: 76b98e95a5b850850baa0ccc3c7fbf7c
|
||||
environments/surveys/edit/auto_progress_rating_and_nps_description: cbf676789b9f3f47e36bdf35fa58282b
|
||||
environments/surveys/edit/auto_save_disabled: f7411fb0dcfb8f7b19b85f0be54f2231
|
||||
environments/surveys/edit/auto_save_disabled_tooltip: 77322e1e866b7d29f7641a88bbd3b681
|
||||
environments/surveys/edit/auto_save_on: 1524d466830b00c5d727c701db404963
|
||||
|
||||
@@ -209,6 +209,7 @@ const baseSurveyProperties = {
|
||||
},
|
||||
],
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: false,
|
||||
isCaptureIpEnabled: false,
|
||||
endings: [
|
||||
{
|
||||
|
||||
@@ -48,6 +48,7 @@ export const selectSurvey = {
|
||||
isVerifyEmailEnabled: true,
|
||||
isSingleResponsePerEmailEnabled: true,
|
||||
isBackButtonHidden: true,
|
||||
isAutoProgressingEnabled: true,
|
||||
isCaptureIpEnabled: true,
|
||||
redirectUrl: true,
|
||||
projectOverwrites: true,
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Zuweisen =",
|
||||
"audience": "Publikum",
|
||||
"auto_close_on_inactivity": "Automatisches Schließen bei Inaktivität",
|
||||
"auto_progress_rating_and_nps": "Bewertungs- und NPS-Fragen automatisch fortsetzen",
|
||||
"auto_progress_rating_and_nps_description": "Fahre automatisch fort, sobald Befragte eine Antwort bei Bewertungs- oder NPS-Fragen auswählen. Dies gilt nur für Blöcke mit einer einzelnen Frage. Bei Pflichtfragen wird die Weiter-Schaltfläche ausgeblendet; bei optionalen Fragen bleibt sie zum Überspringen sichtbar.",
|
||||
"auto_save_disabled": "Automatisches Speichern deaktiviert",
|
||||
"auto_save_disabled_tooltip": "Ihre Umfrage wird nur im Entwurfsmodus automatisch gespeichert. So wird sichergestellt, dass öffentliche Umfragen nicht unbeabsichtigt aktualisiert werden.",
|
||||
"auto_save_on": "Automatisches Speichern an",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Assign =",
|
||||
"audience": "Audience",
|
||||
"auto_close_on_inactivity": "Auto close on inactivity",
|
||||
"auto_progress_rating_and_nps": "Auto-progress rating and NPS questions",
|
||||
"auto_progress_rating_and_nps_description": "Automatically advance when respondents select an answer on rating or NPS questions. This only applies to single-question blocks. Required questions hide the Next button; optional questions still show it for skipping.",
|
||||
"auto_save_disabled": "Auto-save disabled",
|
||||
"auto_save_disabled_tooltip": "Your survey is only auto-saved when in draft. This assures public surveys are not unintentionally updated.",
|
||||
"auto_save_on": "Auto-save on",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Asignar =",
|
||||
"audience": "Audiencia",
|
||||
"auto_close_on_inactivity": "Cierre automático por inactividad",
|
||||
"auto_progress_rating_and_nps": "Avanzar automáticamente en preguntas de valoración y NPS",
|
||||
"auto_progress_rating_and_nps_description": "Avanza automáticamente cuando los encuestados seleccionen una respuesta en preguntas de valoración o NPS. Esto solo se aplica a bloques de una sola pregunta. Las preguntas obligatorias ocultan el botón Siguiente; las preguntas opcionales aún lo muestran para omitirlas.",
|
||||
"auto_save_disabled": "Guardado automático desactivado",
|
||||
"auto_save_disabled_tooltip": "Su encuesta solo se guarda automáticamente cuando está en borrador. Esto asegura que las encuestas públicas no se actualicen involuntariamente.",
|
||||
"auto_save_on": "Guardado automático activado",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Attribuer =",
|
||||
"audience": "Public",
|
||||
"auto_close_on_inactivity": "Fermeture automatique en cas d'inactivité",
|
||||
"auto_progress_rating_and_nps": "Progression automatique pour les questions d'évaluation et NPS",
|
||||
"auto_progress_rating_and_nps_description": "Passe automatiquement à la question suivante lorsque les répondants sélectionnent une réponse aux questions d'évaluation ou NPS. Cela s'applique uniquement aux blocs à question unique. Les questions obligatoires masquent le bouton Suivant ; les questions facultatives l'affichent toujours pour permettre de passer la question.",
|
||||
"auto_save_disabled": "Sauvegarde automatique désactivée",
|
||||
"auto_save_disabled_tooltip": "Votre sondage n'est sauvegardé automatiquement que lorsqu'il est en brouillon. Cela garantit que les sondages publics ne sont pas mis à jour involontairement.",
|
||||
"auto_save_on": "Sauvegarde automatique activée",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "= hozzárendelése",
|
||||
"audience": "Közönség",
|
||||
"auto_close_on_inactivity": "Automatikus lezárás tétlenségnél",
|
||||
"auto_progress_rating_and_nps": "Automatikus továbblépés értékelési és NPS kérdéseknél",
|
||||
"auto_progress_rating_and_nps_description": "Automatikus továbblépés, amikor a válaszadók kiválasztanak egy választ az értékelési vagy NPS kérdéseknél. Ez csak az egykérdéses blokkokra vonatkozik. A kötelező kérdések elrejtik a Tovább gombot; az opcionális kérdések továbbra is megjelenítik azt a kihagyás lehetősége érdekében.",
|
||||
"auto_save_disabled": "Az automatikus mentés letiltva",
|
||||
"auto_save_disabled_tooltip": "A kérdőív csak akkor kerül automatikusan mentésre, ha piszkozatban van. Ez biztosítja, hogy a nyilvános kérdőívek ne legyenek véletlenül frissítve.",
|
||||
"auto_save_on": "Automatikus mentés bekapcsolva",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "割り当て =",
|
||||
"audience": "オーディエンス",
|
||||
"auto_close_on_inactivity": "非アクティブ時に自動閉鎖",
|
||||
"auto_progress_rating_and_nps": "評価とNPSの質問を自動進行",
|
||||
"auto_progress_rating_and_nps_description": "評価またはNPSの質問で回答者が選択肢を選んだ際に自動的に次へ進みます。これは単一質問ブロックにのみ適用されます。必須の質問では「次へ」ボタンが非表示になり、任意の質問ではスキップ用に引き続き表示されます。",
|
||||
"auto_save_disabled": "自動保存が無効",
|
||||
"auto_save_disabled_tooltip": "アンケートは下書き状態の時のみ自動保存されます。これにより、公開中のアンケートが意図せず更新されることを防ぎます。",
|
||||
"auto_save_on": "自動保存オン",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Toewijzen =",
|
||||
"audience": "Publiek",
|
||||
"auto_close_on_inactivity": "Automatisch sluiten bij inactiviteit",
|
||||
"auto_progress_rating_and_nps": "Automatisch doorgaan bij beoordelings- en NPS-vragen",
|
||||
"auto_progress_rating_and_nps_description": "Ga automatisch verder wanneer respondenten een antwoord selecteren bij beoordelings- of NPS-vragen. Dit geldt alleen voor blokken met één vraag. Bij verplichte vragen wordt de Volgende-knop verborgen; bij optionele vragen blijft deze zichtbaar om de vraag over te slaan.",
|
||||
"auto_save_disabled": "Automatisch opslaan uitgeschakeld",
|
||||
"auto_save_disabled_tooltip": "Uw enquête wordt alleen automatisch opgeslagen wanneer deze een concept is. Dit zorgt ervoor dat openbare enquêtes niet onbedoeld worden bijgewerkt.",
|
||||
"auto_save_on": "Automatisch opslaan aan",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "atribuir =",
|
||||
"audience": "Público",
|
||||
"auto_close_on_inactivity": "Fechar automaticamente por inatividade",
|
||||
"auto_progress_rating_and_nps": "Avançar automaticamente em perguntas de avaliação e NPS",
|
||||
"auto_progress_rating_and_nps_description": "Avança automaticamente quando os respondentes selecionam uma resposta em perguntas de avaliação ou NPS. Isso se aplica apenas a blocos com uma única pergunta. Perguntas obrigatórias ocultam o botão Próximo; perguntas opcionais ainda o exibem para permitir pular.",
|
||||
"auto_save_disabled": "Salvamento automático desativado",
|
||||
"auto_save_disabled_tooltip": "Sua pesquisa só é salva automaticamente quando está em rascunho. Isso garante que pesquisas públicas não sejam atualizadas involuntariamente.",
|
||||
"auto_save_on": "Salvamento automático ativado",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Atribuir =",
|
||||
"audience": "Público",
|
||||
"auto_close_on_inactivity": "Fechar automaticamente por inatividade",
|
||||
"auto_progress_rating_and_nps": "Avançar automaticamente em perguntas de classificação e NPS",
|
||||
"auto_progress_rating_and_nps_description": "Avança automaticamente quando os inquiridos selecionam uma resposta em perguntas de classificação ou NPS. Isto aplica-se apenas a blocos com uma única pergunta. Perguntas obrigatórias ocultam o botão Seguinte; perguntas opcionais continuam a mostrá-lo para permitir saltar.",
|
||||
"auto_save_disabled": "Guardar automático desativado",
|
||||
"auto_save_disabled_tooltip": "O seu inquérito só é guardado automaticamente quando está em rascunho. Isto garante que os inquéritos públicos não sejam atualizados involuntariamente.",
|
||||
"auto_save_on": "Guardar automático ativado",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Atribuire =",
|
||||
"audience": "Public",
|
||||
"auto_close_on_inactivity": "Închidere automată la inactivitate",
|
||||
"auto_progress_rating_and_nps": "Avansare automată pentru întrebări de rating și NPS",
|
||||
"auto_progress_rating_and_nps_description": "Avansează automat când respondenții selectează un răspuns la întrebările de rating sau NPS. Aceasta se aplică doar blocurilor cu o singură întrebare. Întrebările obligatorii ascund butonul Următorul; întrebările opționale îl afișează în continuare pentru a permite omiterea.",
|
||||
"auto_save_disabled": "Salvare automată dezactivată",
|
||||
"auto_save_disabled_tooltip": "Chestionarul dvs. este salvat automat doar când este în ciornă. Acest lucru asigură că sondajele publice nu sunt actualizate neintenționat.",
|
||||
"auto_save_on": "Salvare automată activată",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Назначить =",
|
||||
"audience": "Аудитория",
|
||||
"auto_close_on_inactivity": "Автоматически закрывать при бездействии",
|
||||
"auto_progress_rating_and_nps": "Автоматический переход для вопросов с оценкой и NPS",
|
||||
"auto_progress_rating_and_nps_description": "Автоматически переходить к следующему шагу, когда респонденты выбирают ответ в вопросах с оценкой или NPS. Это применяется только к блокам с одним вопросом. В обязательных вопросах кнопка «Далее» скрыта; в необязательных вопросах она остается видимой для пропуска.",
|
||||
"auto_save_disabled": "Автосохранение отключено",
|
||||
"auto_save_disabled_tooltip": "Ваш опрос автоматически сохраняется только в режиме черновика. Это гарантирует, что публичные опросы не будут случайно обновлены.",
|
||||
"auto_save_on": "Автосохранение включено",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "Tilldela =",
|
||||
"audience": "Målgrupp",
|
||||
"auto_close_on_inactivity": "Stäng automatiskt vid inaktivitet",
|
||||
"auto_progress_rating_and_nps": "Gå vidare automatiskt vid betygs- och NPS-frågor",
|
||||
"auto_progress_rating_and_nps_description": "Gå automatiskt vidare när respondenter väljer ett svar på betygs- eller NPS-frågor. Detta gäller endast block med en enda fråga. Obligatoriska frågor döljer Nästa-knappen; valfria frågor visar den fortfarande för att kunna hoppas över.",
|
||||
"auto_save_disabled": "Automatisk sparning inaktiverad",
|
||||
"auto_save_disabled_tooltip": "Din enkät sparas endast automatiskt när den är ett utkast. Detta säkerställer att publika enkäter inte uppdateras oavsiktligt.",
|
||||
"auto_save_on": "Automatisk sparning på",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "指派 =",
|
||||
"audience": "受众",
|
||||
"auto_close_on_inactivity": "自动关闭 在 无活动时",
|
||||
"auto_progress_rating_and_nps": "自动推进评分和 NPS 问题",
|
||||
"auto_progress_rating_and_nps_description": "当受访者在评分或 NPS 问题上选择答案时自动前进。这仅适用于单问题区块。必填问题会隐藏\"下一步\"按钮;可选问题仍会显示该按钮以便跳过。",
|
||||
"auto_save_disabled": "自动保存已禁用",
|
||||
"auto_save_disabled_tooltip": "您的调查仅在草稿状态时自动保存。这确保公开的调查不会被意外更新。",
|
||||
"auto_save_on": "自动保存已启用",
|
||||
|
||||
@@ -1359,6 +1359,8 @@
|
||||
"assign": "等於 =",
|
||||
"audience": "受眾",
|
||||
"auto_close_on_inactivity": "非活動時自動關閉",
|
||||
"auto_progress_rating_and_nps": "自動前進評分與 NPS 問題",
|
||||
"auto_progress_rating_and_nps_description": "當受訪者在評分或 NPS 問題中選擇答案時自動前進。此設定僅適用於單一問題區塊。必填問題會隱藏「下一步」按鈕;選填問題仍會顯示該按鈕以便跳過。",
|
||||
"auto_save_disabled": "自動儲存已停用",
|
||||
"auto_save_disabled_tooltip": "您的問卷僅在草稿狀態時自動儲存。這確保公開的問卷不會被意外更新。",
|
||||
"auto_save_on": "自動儲存已啟用",
|
||||
|
||||
+5
-8
@@ -98,14 +98,11 @@ describe("Users Lib", () => {
|
||||
|
||||
test("returns conflict error if user with email already exists", async () => {
|
||||
(prisma.user.create as any).mockRejectedValueOnce(
|
||||
new Prisma.PrismaClientKnownRequestError(
|
||||
"Unique constraint failed on the fields: (`email`)",
|
||||
{
|
||||
code: PrismaErrorType.UniqueConstraintViolation,
|
||||
clientVersion: "1.0.0",
|
||||
meta: { target: ["email"] },
|
||||
}
|
||||
)
|
||||
new Prisma.PrismaClientKnownRequestError("Unique constraint failed on the fields: (`email`)", {
|
||||
code: PrismaErrorType.UniqueConstraintViolation,
|
||||
clientVersion: "1.0.0",
|
||||
meta: { target: ["email"] },
|
||||
})
|
||||
);
|
||||
const result = await createUser(
|
||||
{ name: "Duplicate", email: "test@example.com", role: "member" },
|
||||
|
||||
@@ -46,9 +46,9 @@ export const OpenIdButton = ({
|
||||
type="button"
|
||||
onClick={handleLogin}
|
||||
variant="secondary"
|
||||
className="relative w-full justify-center">
|
||||
{text ? text : t("auth.continue_with_openid")}
|
||||
{lastUsed && <span className="absolute right-3 text-xs opacity-50">{t("auth.last_used")}</span>}
|
||||
className="w-full items-center justify-center gap-2 px-2">
|
||||
<span className="truncate">{text || t("auth.continue_with_openid")}</span>
|
||||
{lastUsed && <span className="shrink-0 text-xs opacity-50">{t("auth.last_used")}</span>}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -51,7 +51,7 @@ describe("SSO Providers", () => {
|
||||
expect((samlProvider as any).authorization?.url).toBe("https://test-app.com/api/auth/saml/authorize");
|
||||
expect(samlProvider.token).toBe("https://test-app.com/api/auth/saml/token");
|
||||
expect(samlProvider.userinfo).toBe("https://test-app.com/api/auth/saml/userinfo");
|
||||
expect((googleProvider as any).options?.allowDangerousEmailAccountLinking).toBe(true);
|
||||
expect(samlProvider.allowDangerousEmailAccountLinking).toBe(true);
|
||||
expect(googleProvider.allowDangerousEmailAccountLinking).toBeUndefined();
|
||||
expect(samlProvider.allowDangerousEmailAccountLinking).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,7 +26,6 @@ export const getSSOProviders = () => [
|
||||
GoogleProvider({
|
||||
clientId: GOOGLE_CLIENT_ID || "",
|
||||
clientSecret: GOOGLE_CLIENT_SECRET || "",
|
||||
allowDangerousEmailAccountLinking: true,
|
||||
}),
|
||||
AzureAD({
|
||||
clientId: AZUREAD_CLIENT_ID || "",
|
||||
@@ -81,7 +80,6 @@ export const getSSOProviders = () => [
|
||||
clientId: "dummy",
|
||||
clientSecret: "dummy",
|
||||
},
|
||||
allowDangerousEmailAccountLinking: true,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ const LINKED_SSO_LOOKUP_SELECT = {
|
||||
identityProviderAccountId: true,
|
||||
} as const;
|
||||
|
||||
const OAUTH_ACCOUNT_NOT_LINKED_ERROR = "OAuthAccountNotLinked";
|
||||
|
||||
const syncSsoAccount = async (userId: string, account: Account, tx?: Prisma.TransactionClient) => {
|
||||
await upsertAccount(
|
||||
{
|
||||
@@ -217,7 +219,7 @@ export const handleSsoCallback = async ({
|
||||
}
|
||||
|
||||
// There is no existing linked account for this identity provider / account id
|
||||
// check if a user account with this email already exists and auto-link it
|
||||
// check if a user account with this email already exists and fail closed if so
|
||||
contextLogger.debug({ lookupType: "email" }, "No linked SSO account found, checking for user by email");
|
||||
|
||||
const existingUserWithEmail = await getUserByEmail(user.email);
|
||||
@@ -228,10 +230,9 @@ export const handleSsoCallback = async ({
|
||||
existingUserId: existingUserWithEmail.id,
|
||||
existingIdentityProvider: existingUserWithEmail.identityProvider,
|
||||
},
|
||||
"SSO callback successful: existing user found by email"
|
||||
"SSO callback blocked: existing user found by email without linked provider account"
|
||||
);
|
||||
await syncSsoAccount(existingUserWithEmail.id, account);
|
||||
return true;
|
||||
throw new Error(OAUTH_ACCOUNT_NOT_LINKED_ERROR);
|
||||
}
|
||||
|
||||
contextLogger.debug(
|
||||
|
||||
@@ -338,7 +338,7 @@ describe("handleSsoCallback", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should auto-link verified email users whose SSO provider is not already linked", async () => {
|
||||
test("should reject verified email users whose SSO provider is not already linked", async () => {
|
||||
vi.mocked(prisma.user.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(getUserByEmail).mockResolvedValue({
|
||||
id: "existing-user-id",
|
||||
@@ -349,26 +349,22 @@ describe("handleSsoCallback", () => {
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
const result = await handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(upsertAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: "existing-user-id",
|
||||
provider: mockAccount.provider,
|
||||
providerAccountId: mockAccount.providerAccountId,
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
await expect(
|
||||
handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
})
|
||||
).rejects.toThrow("OAuthAccountNotLinked");
|
||||
expect(upsertAccount).not.toHaveBeenCalled();
|
||||
expect(updateUser).not.toHaveBeenCalled();
|
||||
expect(createUser).not.toHaveBeenCalled();
|
||||
expect(createMembership).not.toHaveBeenCalled();
|
||||
expect(createBrevoCustomer).not.toHaveBeenCalled();
|
||||
expect(capturePostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should auto-link unverified email users whose SSO provider is not already linked", async () => {
|
||||
test("should reject unverified email users whose SSO provider is not already linked", async () => {
|
||||
vi.mocked(prisma.account.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.user.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(getUserByEmail).mockResolvedValue({
|
||||
@@ -380,26 +376,22 @@ describe("handleSsoCallback", () => {
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
const result = await handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(upsertAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: "existing-user-id",
|
||||
provider: mockAccount.provider,
|
||||
providerAccountId: mockAccount.providerAccountId,
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
await expect(
|
||||
handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
})
|
||||
).rejects.toThrow("OAuthAccountNotLinked");
|
||||
expect(upsertAccount).not.toHaveBeenCalled();
|
||||
expect(updateUser).not.toHaveBeenCalled();
|
||||
expect(createUser).not.toHaveBeenCalled();
|
||||
expect(createMembership).not.toHaveBeenCalled();
|
||||
expect(createBrevoCustomer).not.toHaveBeenCalled();
|
||||
expect(capturePostHogEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should auto-link existing users from a different SSO provider when no link exists", async () => {
|
||||
test("should reject existing users from a different SSO provider when no link exists", async () => {
|
||||
vi.mocked(prisma.account.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.user.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(getUserByEmail).mockResolvedValue({
|
||||
@@ -411,53 +403,14 @@ describe("handleSsoCallback", () => {
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
const result = await handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(upsertAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: "existing-user-id",
|
||||
provider: mockAccount.provider,
|
||||
providerAccountId: mockAccount.providerAccountId,
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
expect(updateUser).not.toHaveBeenCalled();
|
||||
expect(createUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should auto-link same-email users even when the stored legacy provider account id is stale", async () => {
|
||||
vi.mocked(prisma.account.findUnique).mockResolvedValue(null);
|
||||
vi.mocked(prisma.user.findFirst).mockResolvedValue(null);
|
||||
vi.mocked(getUserByEmail).mockResolvedValue({
|
||||
id: "existing-user-id",
|
||||
email: mockUser.email,
|
||||
emailVerified: new Date(),
|
||||
identityProvider: "google",
|
||||
identityProviderAccountId: "old-provider-id",
|
||||
locale: mockUser.locale,
|
||||
isActive: true,
|
||||
} as any);
|
||||
|
||||
const result = await handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
});
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(upsertAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: "existing-user-id",
|
||||
provider: mockAccount.provider,
|
||||
providerAccountId: mockAccount.providerAccountId,
|
||||
}),
|
||||
undefined
|
||||
);
|
||||
await expect(
|
||||
handleSsoCallback({
|
||||
user: mockUser,
|
||||
account: mockAccount,
|
||||
callbackUrl: "http://localhost:3000",
|
||||
})
|
||||
).rejects.toThrow("OAuthAccountNotLinked");
|
||||
expect(upsertAccount).not.toHaveBeenCalled();
|
||||
expect(updateUser).not.toHaveBeenCalled();
|
||||
expect(createUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -118,6 +118,10 @@ export const ResponseOptionsCard = ({
|
||||
setLocalSurvey({ ...localSurvey, isBackButtonHidden: !localSurvey.isBackButtonHidden });
|
||||
};
|
||||
|
||||
const handleAutoProgressToggle = () => {
|
||||
setLocalSurvey({ ...localSurvey, isAutoProgressingEnabled: !localSurvey.isAutoProgressingEnabled });
|
||||
};
|
||||
|
||||
const handleCaptureIpToggle = () => {
|
||||
setCaptureIpToggle(!captureIpToggle);
|
||||
setLocalSurvey({ ...localSurvey, isCaptureIpEnabled: !localSurvey.isCaptureIpEnabled });
|
||||
@@ -384,6 +388,13 @@ export const ResponseOptionsCard = ({
|
||||
</AdvancedOptionToggle>
|
||||
</>
|
||||
)}
|
||||
<AdvancedOptionToggle
|
||||
htmlId="autoProgressRatingNps"
|
||||
isChecked={Boolean(localSurvey.isAutoProgressingEnabled)}
|
||||
onToggle={handleAutoProgressToggle}
|
||||
title={t("environments.surveys.edit.auto_progress_rating_and_nps")}
|
||||
description={t("environments.surveys.edit.auto_progress_rating_and_nps_description")}
|
||||
/>
|
||||
<AdvancedOptionToggle
|
||||
htmlId="hideBackButton"
|
||||
isChecked={localSurvey.isBackButtonHidden}
|
||||
|
||||
@@ -211,11 +211,15 @@ export const StylingView = ({
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center gap-2 space-y-0">
|
||||
<FormControl>
|
||||
<Switch checked={!!field.value} onCheckedChange={handleOverwriteToggle} />
|
||||
<Switch
|
||||
id="overwrite-theme-styling"
|
||||
checked={!!field.value}
|
||||
onCheckedChange={handleOverwriteToggle}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
<div>
|
||||
<FormLabel className="text-base font-semibold text-slate-900">
|
||||
<FormLabel htmlFor="overwrite-theme-styling" className="text-base font-semibold text-slate-900">
|
||||
{t("environments.surveys.edit.add_custom_styles")}
|
||||
</FormLabel>
|
||||
<FormDescription className="text-sm text-slate-800">
|
||||
|
||||
@@ -41,6 +41,7 @@ export const selectSurvey = {
|
||||
showLanguageSwitch: true,
|
||||
recaptcha: true,
|
||||
isBackButtonHidden: true,
|
||||
isAutoProgressingEnabled: true,
|
||||
metadata: true,
|
||||
slug: true,
|
||||
customHeadScripts: true,
|
||||
|
||||
@@ -79,6 +79,7 @@ describe("data", () => {
|
||||
redirectUrl: null,
|
||||
pin: null,
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: true,
|
||||
singleUse: null,
|
||||
projectOverwrites: null,
|
||||
styling: null,
|
||||
@@ -116,6 +117,11 @@ describe("data", () => {
|
||||
type: true,
|
||||
}),
|
||||
});
|
||||
expect(vi.mocked(prisma.survey.findUnique).mock.calls[0][0].select).toEqual(
|
||||
expect.objectContaining({
|
||||
isAutoProgressingEnabled: true,
|
||||
})
|
||||
);
|
||||
expect(transformPrismaSurvey).toHaveBeenCalledWith(mockSurveyData);
|
||||
});
|
||||
|
||||
@@ -196,6 +202,7 @@ describe("data", () => {
|
||||
redirectUrl: null,
|
||||
pin: null,
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: true,
|
||||
singleUse: null,
|
||||
projectOverwrites: null,
|
||||
surveyClosedMessage: null,
|
||||
|
||||
@@ -47,6 +47,7 @@ export const getSurveyWithMetadata = reactCache(async (surveyId: string) => {
|
||||
redirectUrl: true,
|
||||
pin: true,
|
||||
isBackButtonHidden: true,
|
||||
isAutoProgressingEnabled: true,
|
||||
isCaptureIpEnabled: true,
|
||||
|
||||
// Single use configuration
|
||||
|
||||
@@ -41,6 +41,7 @@ export const getMinimalSurvey = (t: TFunction): TSurvey => ({
|
||||
variables: [],
|
||||
followUps: [],
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: true,
|
||||
metadata: {},
|
||||
slug: null,
|
||||
isCaptureIpEnabled: false,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Skeleton } from "@/modules/ui/components/skeleton";
|
||||
|
||||
type SkeletonLoaderProps = {
|
||||
type: "response" | "summary";
|
||||
type: "response" | "responseTable" | "summary";
|
||||
};
|
||||
|
||||
export const SkeletonLoader = ({ type }: SkeletonLoaderProps) => {
|
||||
@@ -25,6 +25,43 @@ export const SkeletonLoader = ({ type }: SkeletonLoaderProps) => {
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "responseTable") {
|
||||
const renderTableCells = () => (
|
||||
<>
|
||||
<Skeleton className="h-4 w-4 rounded-xl bg-slate-400" />
|
||||
<Skeleton className="h-4 w-24 rounded-xl bg-slate-200" />
|
||||
<Skeleton className="h-4 w-32 rounded-xl bg-slate-200" />
|
||||
<Skeleton className="h-4 w-40 rounded-xl bg-slate-200" />
|
||||
<Skeleton className="h-4 w-40 rounded-xl bg-slate-200" />
|
||||
<Skeleton className="h-4 w-32 rounded-xl bg-slate-200" />
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="animate-pulse space-y-4" data-testid="skeleton-loader-response-table">
|
||||
<div className="flex items-center justify-between">
|
||||
<Skeleton className="h-8 w-48 rounded-md bg-slate-300" />
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-8 w-8 rounded-md bg-slate-300" />
|
||||
<Skeleton className="h-8 w-8 rounded-md bg-slate-300" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-xl border border-slate-200">
|
||||
<div className="flex h-12 items-center gap-4 border-b border-slate-200 bg-slate-100 px-4">
|
||||
{renderTableCells()}
|
||||
</div>
|
||||
{Array.from({ length: 10 }, (_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex h-12 items-center gap-4 border-b border-slate-100 px-4 last:border-b-0">
|
||||
{renderTableCells()}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === "response") {
|
||||
return (
|
||||
<div className="group space-y-4 rounded-lg bg-white p-6" data-testid="skeleton-loader-response">
|
||||
|
||||
@@ -5631,6 +5631,9 @@ components:
|
||||
isBackButtonHidden:
|
||||
type: boolean
|
||||
description: Whether the back button is hidden
|
||||
isAutoProgressingEnabled:
|
||||
type: boolean
|
||||
description: Whether auto-progress is enabled for eligible question types
|
||||
recaptcha:
|
||||
type:
|
||||
- object
|
||||
@@ -5706,6 +5709,7 @@ components:
|
||||
- isSingleResponsePerEmailEnabled
|
||||
- inlineTriggers
|
||||
- isBackButtonHidden
|
||||
- isAutoProgressingEnabled
|
||||
- recaptcha
|
||||
- metadata
|
||||
- displayPercentage
|
||||
|
||||
@@ -0,0 +1,401 @@
|
||||
---
|
||||
title: "Background Job Processing"
|
||||
description: "How BullMQ works in Formbricks today, including the migrated response pipeline workload."
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
This page documents the current BullMQ-based background job system in Formbricks and the first real workload that now runs on it: the response pipeline.
|
||||
|
||||
## Current State
|
||||
|
||||
Formbricks now uses BullMQ as an in-process background job system inside the Next.js web application.
|
||||
|
||||
The current implementation includes:
|
||||
|
||||
- a shared `@formbricks/jobs` package that owns queue creation, schemas, scheduling, and worker runtime concerns
|
||||
- a Next.js startup hook that starts one BullMQ worker runtime per Node.js process without blocking app boot
|
||||
- app-level enqueue helpers for request handlers
|
||||
- an app-owned BullMQ response pipeline processor that replaces the legacy internal HTTP pipeline route
|
||||
|
||||
The first migrated workload is:
|
||||
|
||||
- `response-pipeline.process`
|
||||
|
||||
This means response-related side effects no longer depend on an internal `fetch()` back into the same app process.
|
||||
|
||||
## Why This Exists
|
||||
|
||||
The original response pipeline lived behind an internal Next.js route:
|
||||
|
||||
```text
|
||||
apps/web/app/api/(internal)/pipeline
|
||||
```
|
||||
|
||||
That model had a few problems:
|
||||
|
||||
- it was tightly coupled to the request lifecycle
|
||||
- it relied on an internal HTTP hop instead of a typed background-job boundary
|
||||
- it was harder to observe, retry, and scale safely
|
||||
|
||||
BullMQ addresses that by moving post-response work behind a queue while keeping the first version operationally simple for self-hosted users.
|
||||
|
||||
## High-Level Architecture
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A["API route or server code"] --> B["enqueueResponsePipelineEvents()"]
|
||||
B --> C["getResponseSnapshotForPipeline()"]
|
||||
B --> D["BackgroundJobProducer.enqueueResponsePipeline()"]
|
||||
D --> E["BullMQ queue: background-jobs"]
|
||||
F["instrumentation.ts"] --> G["registerJobsWorker()"]
|
||||
G --> H["startJobsRuntime()"]
|
||||
H --> I["BullMQ workers"]
|
||||
I --> J["response-pipeline.process override"]
|
||||
J --> K["processResponsePipelineJob()"]
|
||||
E --> I
|
||||
E --> L["Redis / Valkey"]
|
||||
I --> L
|
||||
```
|
||||
|
||||
## Responsibilities By Layer
|
||||
|
||||
### App Layer
|
||||
|
||||
- `apps/web/app/lib/pipelines.ts`
|
||||
Owns enqueueing for response pipeline events. It gates queueing, hydrates the response snapshot once, logs failures, and never throws back into request handlers.
|
||||
- `apps/web/modules/response-pipeline/lib/process-response-pipeline-job.ts`
|
||||
Owns app-specific execution of response-pipeline jobs.
|
||||
- `apps/web/modules/response-pipeline/lib/handle-integrations.ts`
|
||||
Owns Slack, Notion, Airtable, and Google Sheets integration fan-out for the pipeline.
|
||||
- `apps/web/modules/response-pipeline/lib/telemetry.ts`
|
||||
Owns telemetry dispatch logic used by the response-created path.
|
||||
- `apps/web/instrumentation-jobs.ts`
|
||||
Registers the app-owned response-pipeline handler override with the shared BullMQ runtime and schedules retry after transient startup failures.
|
||||
- `apps/web/lib/jobs/config.ts`
|
||||
Turns environment configuration into queueing and worker-bootstrap decisions. Queue producers depend on `REDIS_URL`; worker startup additionally depends on `BULLMQ_WORKER_ENABLED`.
|
||||
|
||||
### Shared Jobs Layer
|
||||
|
||||
- `packages/jobs/src/types.ts`
|
||||
Defines typed payload schemas such as `TResponsePipelineJobData`.
|
||||
- `packages/jobs/src/definitions.ts`
|
||||
Defines stable job names and payload validation.
|
||||
- `packages/jobs/src/queue.ts`
|
||||
Owns producer-side enqueueing and scheduling.
|
||||
- `packages/jobs/src/runtime.ts`
|
||||
Starts workers, connects Redis, and handles graceful shutdown.
|
||||
- `packages/jobs/src/processors/registry.ts`
|
||||
Validates payloads and dispatches named jobs, applying app-provided handler overrides when registered.
|
||||
|
||||
## Response Pipeline Flow
|
||||
|
||||
The response pipeline now runs fully in the background worker.
|
||||
|
||||
### Enqueueing
|
||||
|
||||
When a response is created or updated, the request path calls:
|
||||
|
||||
```ts
|
||||
enqueueResponsePipelineEvents({
|
||||
environmentId,
|
||||
surveyId,
|
||||
responseId,
|
||||
events,
|
||||
});
|
||||
```
|
||||
|
||||
That helper:
|
||||
|
||||
1. deduplicates requested events
|
||||
2. checks whether BullMQ queueing is enabled
|
||||
3. uses the just-written response snapshot when the caller already has it
|
||||
4. otherwise loads the latest response snapshot once via `getResponseSnapshotForPipeline(responseId)` using an uncached read
|
||||
5. enqueues one BullMQ job per event with the shared snapshot payload
|
||||
6. waits for the enqueue attempt to complete, then logs enqueue failures without failing the original request
|
||||
|
||||
### Execution
|
||||
|
||||
At worker startup, `apps/web/instrumentation-jobs.ts` registers an app-owned override for:
|
||||
|
||||
- `response-pipeline.process`
|
||||
|
||||
That override delegates to `processResponsePipelineJob(...)`, which performs:
|
||||
|
||||
- webhook delivery for all pipeline events
|
||||
- integrations for `responseFinished`
|
||||
- response-finished notification emails
|
||||
- follow-up delivery
|
||||
- survey auto-complete updates and audit logging
|
||||
- response-created billing metering
|
||||
- response-created telemetry dispatch
|
||||
|
||||
Current retry semantics are intentionally asymmetric:
|
||||
|
||||
- webhook delivery failures fail early BullMQ attempts so retries can happen at the job level
|
||||
- if webhook delivery is still failing on the final BullMQ attempt, the worker logs that retries are exhausted and continues with the remaining event-specific side effects
|
||||
- integration, email, telemetry, metering, follow-up, and survey auto-complete failures are logged inside the processor and do not fail the whole job
|
||||
|
||||
## Acceptance Criteria Review
|
||||
|
||||
### Pipeline Execution
|
||||
|
||||
Satisfied.
|
||||
|
||||
- New response create/update flows enqueue BullMQ jobs instead of calling an internal HTTP route.
|
||||
- The job payload contains `environmentId`, `surveyId`, `event`, and an authoritative response snapshot.
|
||||
- The response pipeline executes inside the BullMQ worker runtime.
|
||||
|
||||
### Feature Parity
|
||||
|
||||
Mostly satisfied for the legacy response pipeline behavior that existed in the old route.
|
||||
|
||||
The migrated BullMQ processor preserves:
|
||||
|
||||
- webhook delivery
|
||||
- integrations
|
||||
- response-finished emails
|
||||
- follow-up execution
|
||||
- survey auto-complete and audit logging
|
||||
- response-created billing metering
|
||||
- response-created telemetry
|
||||
|
||||
One important behavior change still exists today:
|
||||
|
||||
- webhook delivery failures delay the remaining side effects until the final BullMQ attempt
|
||||
|
||||
That is closer to the legacy route, because the pipeline eventually continues even if webhook delivery never succeeds. It is still not exact feature parity, though, because the legacy route continued immediately while the BullMQ worker waits until retries are exhausted before it degrades webhook failure into a logged condition.
|
||||
|
||||
### Architecture
|
||||
|
||||
Satisfied.
|
||||
|
||||
- Enqueueing lives in the app layer through `apps/web/app/lib/pipelines.ts`.
|
||||
- Execution lives in the worker path under `apps/web/modules/response-pipeline/lib`.
|
||||
- `@formbricks/jobs` stays responsible for queue/runtime concerns and typed job contracts.
|
||||
|
||||
### Cleanup
|
||||
|
||||
Satisfied.
|
||||
|
||||
The legacy internal route has been removed:
|
||||
|
||||
```text
|
||||
apps/web/app/api/(internal)/pipeline/route.ts
|
||||
```
|
||||
|
||||
The runtime path no longer depends on the old internal-route folder structure, and the remaining pipeline-only test mock under that deleted folder has been removed as part of the migration cleanup.
|
||||
|
||||
### Reliability
|
||||
|
||||
Satisfied at the current ticket scope.
|
||||
|
||||
BullMQ jobs use shared default retry behavior:
|
||||
|
||||
- `attempts: 3`
|
||||
- exponential backoff starting at `1000ms`
|
||||
|
||||
Failures are logged with structured metadata such as:
|
||||
|
||||
- `jobId`
|
||||
- `attempt`
|
||||
- `jobName`
|
||||
- `queueName`
|
||||
- `environmentId`
|
||||
- `surveyId`
|
||||
- `responseId`
|
||||
|
||||
Request handlers remain non-blocking:
|
||||
|
||||
- if Redis is unavailable
|
||||
- if queueing is disabled
|
||||
- if snapshot hydration fails
|
||||
- if enqueueing fails
|
||||
|
||||
the request still completes, and the failure is logged.
|
||||
|
||||
Worker startup is also non-blocking:
|
||||
|
||||
- Next.js boot does not await BullMQ readiness
|
||||
- startup failures are logged
|
||||
- the web app schedules a retry instead of requiring an immediate process restart
|
||||
|
||||
### Worker Integration
|
||||
|
||||
Satisfied.
|
||||
|
||||
The response pipeline is processed by the same BullMQ worker runtime started from Next.js instrumentation. No standalone worker service was introduced as part of this migration.
|
||||
|
||||
### Developer Experience
|
||||
|
||||
Satisfied.
|
||||
|
||||
The public app-level API for request handlers is intentionally small:
|
||||
|
||||
- `enqueueResponsePipelineEvents(...)`
|
||||
|
||||
This keeps queue names, Redis concerns, and BullMQ details out of response routes.
|
||||
|
||||
## Comparison With The Legacy Route
|
||||
|
||||
### Previous Implementation
|
||||
|
||||
The legacy internal route accepted a full response payload directly and then executed the entire pipeline synchronously inside the route handler.
|
||||
|
||||
Key characteristics of that model:
|
||||
|
||||
- request handlers performed an internal authenticated `fetch()` back into the same app
|
||||
- the route received the response payload directly instead of hydrating it from a queue-side snapshot
|
||||
- webhook failures were logged and did not block the rest of the pipeline
|
||||
- response-finished integrations, emails, follow-ups, and survey auto-complete ran in the same route execution
|
||||
- response-created metering was fire-and-forget while telemetry was awaited
|
||||
|
||||
### Current BullMQ Implementation
|
||||
|
||||
The current branch enqueues a typed snapshot-based BullMQ job and executes the pipeline inside the in-process worker registered from Next.js instrumentation.
|
||||
|
||||
Key characteristics of the current model:
|
||||
|
||||
- request handlers enqueue directly through `enqueueResponsePipelineEvents(...)`
|
||||
- handlers now pass the just-written `TResponse` snapshot when they already have it
|
||||
- callers that do not already have a response snapshot use an uncached pipeline-specific lookup
|
||||
- worker startup is non-blocking and retries after transient failures
|
||||
- webhook failures fail early attempts so BullMQ can retry them
|
||||
- on the final attempt, webhook failures are logged and the remaining side effects continue
|
||||
- response-created metering is awaited before the BullMQ job completes
|
||||
|
||||
### Net Result
|
||||
|
||||
Compared to the legacy route, the current branch is:
|
||||
|
||||
- architecturally stronger
|
||||
- safer to scale and operate
|
||||
- easier to observe through structured job logging
|
||||
- closer to legacy feature parity than the earlier BullMQ iterations on this branch
|
||||
|
||||
The main remaining semantic difference is timing:
|
||||
|
||||
- the legacy route continued past webhook failures immediately
|
||||
- the BullMQ worker now continues only after webhook retries are exhausted
|
||||
|
||||
That is an intentional trade-off in the current branch, not an accident.
|
||||
|
||||
## Current Queue Model
|
||||
|
||||
The queue remains intentionally small:
|
||||
|
||||
- queue name: `background-jobs`
|
||||
- prefix: `formbricks:jobs`
|
||||
- job names:
|
||||
- `system.test-log`
|
||||
- `response-pipeline.process`
|
||||
|
||||
The response pipeline is the first production workload on this queue.
|
||||
|
||||
## Local Development
|
||||
|
||||
Local development works end to end as long as Redis is available and the worker is enabled.
|
||||
|
||||
Required inputs:
|
||||
|
||||
- `REDIS_URL`
|
||||
- optionally `BULLMQ_WORKER_ENABLED`
|
||||
- optionally `BULLMQ_WORKER_COUNT`
|
||||
- optionally `BULLMQ_WORKER_CONCURRENCY`
|
||||
|
||||
Behavior:
|
||||
|
||||
- if `REDIS_URL` is missing, queueing is skipped
|
||||
- if `BULLMQ_WORKER_ENABLED=0`, the worker is not started, but request-side enqueueing can still stay enabled in deployments that point at a separate BullMQ worker
|
||||
- outside tests, the worker is enabled by default
|
||||
|
||||
This makes it possible to develop request flows without hard-failing when Redis is absent, while still supporting full local end-to-end verification when Redis is running.
|
||||
|
||||
## Operational Notes
|
||||
|
||||
### Logging
|
||||
|
||||
The current implementation logs:
|
||||
|
||||
- worker startup failures
|
||||
- Redis connection failures
|
||||
- enqueue failures
|
||||
- job failures
|
||||
- webhook delivery failures
|
||||
- integration failures
|
||||
- email delivery failures
|
||||
- follow-up failures
|
||||
- survey auto-complete update failures
|
||||
- metering failures
|
||||
- telemetry failures
|
||||
|
||||
### Shutdown
|
||||
|
||||
The worker runtime registers `SIGTERM` and `SIGINT` handlers, closes workers and queue handles, and then closes Redis connections. This keeps shutdown behavior predictable inside the web process.
|
||||
|
||||
## Current Limitations
|
||||
|
||||
The migration satisfies the ticket, but a few larger architectural limits remain by design.
|
||||
|
||||
### Dual-Write Boundary
|
||||
|
||||
Response writes happen in Postgres and background jobs are enqueued in Redis. Those are separate systems, so this remains a dual-write boundary.
|
||||
|
||||
This means Formbricks currently has:
|
||||
|
||||
- non-blocking enqueue semantics
|
||||
- at-least-once background execution
|
||||
- no transactional guarantee that the product write and Redis enqueue succeed together
|
||||
|
||||
That trade-off was accepted for this BullMQ phase.
|
||||
|
||||
### In-Process Workers
|
||||
|
||||
Workers run inside the Next.js app process.
|
||||
|
||||
That keeps self-hosting simple, but it also means:
|
||||
|
||||
- job capacity still shares resources with the web process
|
||||
- heavy background work is still Node.js-local
|
||||
- scaling job throughput also scales the app runtime
|
||||
|
||||
### Webhook-Gated Retries
|
||||
|
||||
Webhook delivery still happens before the rest of the `responseFinished` side effects.
|
||||
|
||||
That gives Formbricks job-level retries for webhook delivery, but it also means:
|
||||
|
||||
- `responseFinished` side effects do not run on the early retry attempts
|
||||
- the remaining side effects only continue after webhook retries are exhausted
|
||||
- this is closer to legacy behavior than failing forever, but it is still not immediate parity
|
||||
|
||||
This is the current behavior of the branch and should be evaluated explicitly if we want stricter feature parity with the legacy route.
|
||||
|
||||
### Logs-First Observability
|
||||
|
||||
The current system has strong structured logging, but it does not yet provide:
|
||||
|
||||
- queue dashboards
|
||||
- retry tooling
|
||||
- latency metrics
|
||||
- product-native workflow inspection
|
||||
|
||||
Those are future improvements, not blockers for the current migration.
|
||||
|
||||
## Recommended Next Steps
|
||||
|
||||
Now that the response pipeline is on BullMQ, the most useful next steps are:
|
||||
|
||||
1. migrate additional low-risk async workloads behind the same producer/runtime boundary
|
||||
2. add queue metrics and worker health visibility beyond logs
|
||||
3. define explicit idempotency rules for side-effect-heavy jobs
|
||||
4. decide which future workloads should remain Node-local and which should eventually move to a different runtime
|
||||
|
||||
## Practical Conclusion
|
||||
|
||||
Formbricks now has:
|
||||
|
||||
- a production-capable BullMQ foundation
|
||||
- a real migrated workload
|
||||
- a clean separation between request-time enqueueing and background execution
|
||||
|
||||
The response pipeline migration should be considered complete for the current ticket scope.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "Survey"
|
||||
ADD COLUMN "isAutoProgressingEnabled" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -395,6 +395,7 @@ model Survey {
|
||||
isVerifyEmailEnabled Boolean @default(false)
|
||||
isSingleResponsePerEmailEnabled Boolean @default(false)
|
||||
isBackButtonHidden Boolean @default(false)
|
||||
isAutoProgressingEnabled Boolean @default(false)
|
||||
isCaptureIpEnabled Boolean @default(false)
|
||||
pin String?
|
||||
displayPercentage Decimal?
|
||||
|
||||
@@ -138,6 +138,7 @@ const ZSurveyBase = z.object({
|
||||
isSingleResponsePerEmailEnabled: z.boolean().describe("Whether single response per email is enabled"),
|
||||
inlineTriggers: z.array(z.any()).nullable().describe("Inline triggers configuration"),
|
||||
isBackButtonHidden: z.boolean().describe("Whether the back button is hidden"),
|
||||
isAutoProgressingEnabled: z.boolean().describe("Whether auto-progress is enabled for eligible questions"),
|
||||
recaptcha: ZSurveyRecaptcha.describe("Google reCAPTCHA configuration"),
|
||||
metadata: ZSurveyMetadata.describe("Custom link metadata for social sharing"),
|
||||
displayPercentage: z.number().nullable().describe("The display percentage of the survey"),
|
||||
|
||||
@@ -79,4 +79,5 @@ export const mockSurvey: TEnvironmentStateSurvey = {
|
||||
brandColor: { light: "#2B6CB0" },
|
||||
},
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: false,
|
||||
};
|
||||
|
||||
@@ -20,6 +20,7 @@ export type TEnvironmentStateSurvey = Pick<
|
||||
| "delay"
|
||||
| "projectOverwrites"
|
||||
| "isBackButtonHidden"
|
||||
| "isAutoProgressingEnabled"
|
||||
| "recaptcha"
|
||||
> & {
|
||||
languages: (SurveyLanguage & { language: Language })[];
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
import { S3Client, type S3ClientConfig } from "@aws-sdk/client-s3";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("@formbricks/logger", () => ({
|
||||
logger: {
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock the AWS SDK S3Client
|
||||
vi.mock("@aws-sdk/client-s3", () => ({
|
||||
S3Client: vi.fn(function MockS3Client(
|
||||
|
||||
@@ -11,6 +11,15 @@ import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("@formbricks/logger", () => ({
|
||||
logger: {
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
info: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
type Paginator<T> = AsyncGenerator<T, undefined, unknown>;
|
||||
|
||||
// Mock AWS SDK modules
|
||||
|
||||
@@ -4,16 +4,17 @@ import * as React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-button text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 aria-invalid:border-destructive",
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-button text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20",
|
||||
outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
custom: "button-custom",
|
||||
},
|
||||
|
||||
@@ -225,7 +225,7 @@ function CalendarDayButton({
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-brand data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground hover:text-primary-foreground data-[selected-single=true]:hover:bg-brand data-[selected-single=true]:hover:text-primary-foreground data-[range-start=true]:hover:bg-primary data-[range-start=true]:hover:text-primary-foreground data-[range-end=true]:hover:bg-primary data-[range-end=true]:hover:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] hover:bg-[color-mix(in_srgb,var(--fb-survey-brand-color)_70%,transparent)] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
"data-[selected-single=true]:bg-brand data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground hover:text-primary-foreground data-[selected-single=true]:hover:bg-brand data-[selected-single=true]:hover:text-primary-foreground data-[range-start=true]:hover:bg-primary data-[range-start=true]:hover:text-primary-foreground data-[range-end=true]:hover:bg-primary data-[range-end=true]:hover:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square h-auto w-full min-w-[--cell-size] flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] hover:bg-[color-mix(in_srgb,var(--fb-survey-brand-color)_70%,transparent)] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
|
||||
@@ -11,7 +11,7 @@ function Checkbox({
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"border-input-border data-[state=checked]:bg-brand data-[state=checked]:text-brand-foreground data-[state=checked]:border-brand focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 aria-invalid:border-destructive text-input-text peer size-4 shrink-0 rounded-[4px] border bg-white shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
"border-input-border dark:bg-input/30 data-[state=checked]:bg-brand data-[state=checked]:text-brand-foreground dark:data-[state=checked]:bg-brand data-[state=checked]:border-brand focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive text-input-text peer size-4 shrink-0 rounded-[4px] border bg-white shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}>
|
||||
|
||||
@@ -58,7 +58,7 @@ function DropdownMenuItem({
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none focus-visible:outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none focus-visible:outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -41,7 +41,7 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(function Input(
|
||||
// Focus ring
|
||||
"focus-visible:border-ring focus-visible:ring-ring focus-visible:ring-[3px]",
|
||||
// Error state ring
|
||||
"aria-invalid:ring-destructive/20 aria-invalid:border-destructive",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
// Disabled state
|
||||
"disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
|
||||
@@ -31,7 +31,7 @@ function RadioGroupItem({
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"border-input-border text-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 aria-invalid:border-destructive aspect-square size-4 shrink-0 rounded-full border bg-white shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
"border-input-border text-input focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border bg-white shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}>
|
||||
|
||||
@@ -13,7 +13,7 @@ function Textarea({ className, dir = "auto", ...props }: TextareaProps): React.J
|
||||
style={{ fontSize: "var(--fb-input-font-size)" }}
|
||||
dir={dir}
|
||||
className={cn(
|
||||
"w-input bg-input-bg border-input-border rounded-input font-input font-input-weight px-input-x py-input-y shadow-input placeholder:text-input-placeholder placeholder:opacity-input-placeholder focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 aria-invalid:border-destructive text-input text-input-text flex field-sizing-content min-h-16 border transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
"w-input bg-input-bg border-input-border rounded-input font-input font-input-weight px-input-x py-input-y shadow-input placeholder:text-input-placeholder placeholder:opacity-input-placeholder focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 text-input text-input-text flex field-sizing-content min-h-16 border transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
import { cn } from "./utils";
|
||||
|
||||
vi.mock("isomorphic-dompurify", () => ({
|
||||
sanitize: vi.fn((value: string) => value),
|
||||
}));
|
||||
|
||||
describe("cn", () => {
|
||||
test("merges class names correctly", () => {
|
||||
expect(cn("foo", "bar")).toBe("foo bar");
|
||||
|
||||
@@ -64,6 +64,7 @@
|
||||
"autoprefixer": "10.4.27",
|
||||
"concurrently": "9.2.1",
|
||||
"fake-indexeddb": "6.2.5",
|
||||
"happy-dom": "20.8.9",
|
||||
"postcss": "8.5.8",
|
||||
"rollup-plugin-visualizer": "7.0.1",
|
||||
"tailwindcss": "4.2.1",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// basic regex -- [whitespace](number)(rem)[whitespace or ;]
|
||||
const REM_REGEX = /\b(\d+(\.\d+)?)(rem)\b/gi;
|
||||
// Matches a CSS numeric value followed by "rem" — e.g. "1rem", "1.5rem", "16rem".
|
||||
// Single character-class + single quantifier: no nested quantifiers, no backtracking risk.
|
||||
const REM_REGEX = /([\d.]+)(rem)/gi; // NOSONAR -- single character-class quantifier on trusted CSS input; no backtracking risk
|
||||
const PROCESSED = Symbol("processed");
|
||||
|
||||
const remtoEm = (opts = {}) => {
|
||||
@@ -26,6 +27,36 @@ const remtoEm = (opts = {}) => {
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
plugins: [require("@tailwindcss/postcss"), require("autoprefixer"), remtoEm()],
|
||||
// Strips the `@layer properties { ... }` block that Tailwind v4 emits as a
|
||||
// browser-compatibility fallback for `@property` declarations.
|
||||
//
|
||||
// Problem: CSS `@layer` at-rules are globally scoped by spec — they cannot be
|
||||
// confined by a surrounding selector. Even though all other Formbricks survey
|
||||
// styles are correctly scoped to `#fbjs`, the `@layer properties` block
|
||||
// contains a bare `*, :before, :after, ::backdrop` selector that resets all
|
||||
// `--tw-*` CSS custom properties on every element of the host page. This
|
||||
// breaks shadows, rings, transforms, and other Tailwind utilities on any site
|
||||
// that uses Tailwind v4 alongside the Formbricks SDK.
|
||||
//
|
||||
// The `@property` declarations already present in the same stylesheet cover
|
||||
// the same browser-compatibility need for all supporting browsers, so removing
|
||||
// `@layer properties` does not affect survey rendering.
|
||||
//
|
||||
// See: https://github.com/formbricks/js/issues/46
|
||||
const stripLayerProperties = () => {
|
||||
return {
|
||||
postcssPlugin: "postcss-strip-layer-properties",
|
||||
AtRule: {
|
||||
layer: (atRule) => {
|
||||
if (atRule.params === "properties") {
|
||||
atRule.remove();
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
stripLayerProperties.postcss = true;
|
||||
|
||||
module.exports = {
|
||||
plugins: [require("@tailwindcss/postcss"), require("autoprefixer"), remtoEm(), stripLayerProperties()],
|
||||
};
|
||||
|
||||
@@ -11,6 +11,11 @@ import { BackButton } from "@/components/buttons/back-button";
|
||||
import { SubmitButton } from "@/components/buttons/submit-button";
|
||||
import { ElementConditional } from "@/components/general/element-conditional";
|
||||
import { ScrollableContainer } from "@/components/wrappers/scrollable-container";
|
||||
import {
|
||||
getAutoProgressElement,
|
||||
shouldHideSubmitButtonForAutoProgress,
|
||||
shouldTriggerAutoProgress,
|
||||
} from "@/lib/auto-progress";
|
||||
import { getLocalizedValue } from "@/lib/i18n";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getFirstErrorMessage, validateBlockResponses } from "@/lib/validation/evaluator";
|
||||
@@ -32,6 +37,7 @@ interface BlockConditionalProps {
|
||||
surveyId: string;
|
||||
autoFocusEnabled: boolean;
|
||||
isBackButtonHidden: boolean;
|
||||
isAutoProgressingEnabled: boolean;
|
||||
onOpenExternalURL?: (url: string) => void | Promise<void>;
|
||||
dir?: "ltr" | "rtl" | "auto";
|
||||
fullSizeCards: boolean;
|
||||
@@ -55,6 +61,7 @@ export function BlockConditional({
|
||||
onFileUpload,
|
||||
autoFocusEnabled,
|
||||
isBackButtonHidden,
|
||||
isAutoProgressingEnabled,
|
||||
onOpenExternalURL,
|
||||
dir,
|
||||
fullSizeCards,
|
||||
@@ -71,6 +78,12 @@ export function BlockConditional({
|
||||
|
||||
// Ref to collect TTC values synchronously (state updates are async)
|
||||
const ttcCollectorRef = useRef<TResponseTtc>({});
|
||||
const autoProgressingInFlightRef = useRef(false);
|
||||
const autoProgressElement = getAutoProgressElement(block.elements, isAutoProgressingEnabled);
|
||||
const shouldHideSubmitButton = shouldHideSubmitButtonForAutoProgress(
|
||||
block.elements,
|
||||
isAutoProgressingEnabled
|
||||
);
|
||||
|
||||
// Handle change for an individual element
|
||||
const handleElementChange = (elementId: string, responseData: TResponseData) => {
|
||||
@@ -86,8 +99,37 @@ export function BlockConditional({
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
const mergedValue = { ...value, ...responseData };
|
||||
const blockResponses = block.elements.reduce<TResponseData>((acc, element) => {
|
||||
const elementValue = mergedValue[element.id];
|
||||
if (elementValue !== undefined) {
|
||||
acc[element.id] = elementValue;
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
// Merge with existing block data to preserve other element values
|
||||
onChange({ ...value, ...responseData });
|
||||
onChange(mergedValue);
|
||||
|
||||
if (
|
||||
shouldTriggerAutoProgress({
|
||||
changedElementId: elementId,
|
||||
mergedValue,
|
||||
autoProgressElement,
|
||||
isAlreadyInFlight: autoProgressingInFlightRef.current,
|
||||
})
|
||||
) {
|
||||
autoProgressingInFlightRef.current = true;
|
||||
// Defer submission so element-level change handlers can finalize TTC updates first.
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const blockTtc = collectTtcValues();
|
||||
onSubmit(blockResponses, blockTtc);
|
||||
} finally {
|
||||
autoProgressingInFlightRef.current = false;
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
};
|
||||
|
||||
// Handler to collect TTC values synchronously (called from element form submissions)
|
||||
@@ -218,9 +260,7 @@ export function BlockConditional({
|
||||
for (const element of block.elements) {
|
||||
const form = elementFormRefs.current.get(element.id);
|
||||
if (form && !validateElementForm(element, form)) {
|
||||
if (!firstInvalidForm) {
|
||||
firstInvalidForm = form;
|
||||
}
|
||||
firstInvalidForm ??= form;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,14 +390,19 @@ export function BlockConditional({
|
||||
fullSizeCards ? "bg-survey-bg sticky bottom-0" : ""
|
||||
)}>
|
||||
<div>
|
||||
<SubmitButton
|
||||
buttonLabel={
|
||||
block.buttonLabel ? getLocalizedValue(block.buttonLabel, languageCode) : undefined
|
||||
}
|
||||
isLastQuestion={isLastBlock}
|
||||
onClick={handleBlockSubmit}
|
||||
tabIndex={0}
|
||||
/>
|
||||
{shouldHideSubmitButton ? (
|
||||
// Keep layout symmetry for Back button positioning (LTR/RTL).
|
||||
<div aria-hidden="true" className="mb-1 h-(--fb-button-height)" />
|
||||
) : (
|
||||
<SubmitButton
|
||||
buttonLabel={
|
||||
block.buttonLabel ? getLocalizedValue(block.buttonLabel, languageCode) : undefined
|
||||
}
|
||||
isLastQuestion={isLastBlock}
|
||||
onClick={handleBlockSubmit}
|
||||
tabIndex={0}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{!isFirstBlock && !isBackButtonHidden && (
|
||||
<BackButton
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
type SerializedSurveyState,
|
||||
clearSurveyProgress,
|
||||
getSurveyProgress,
|
||||
patchSurveyProgressSnapshot,
|
||||
saveSurveyProgress,
|
||||
} from "@/lib/offline-storage";
|
||||
import { parseRecallInformation } from "@/lib/recall";
|
||||
@@ -39,28 +38,13 @@ import { useOnlineStatus } from "@/lib/use-online-status";
|
||||
import { cn, findBlockByElementId, getDefaultLanguageCode, getElementsFromSurveyBlocks } from "@/lib/utils";
|
||||
import { TResponseErrorCodesEnum } from "@/types/response-error-codes";
|
||||
|
||||
const restoreSurveyStateFromSnapshot = (
|
||||
surveyState: SurveyState,
|
||||
snapshot: SerializedSurveyState,
|
||||
progress: {
|
||||
responseData: TResponseData;
|
||||
ttc: TResponseTtc;
|
||||
currentVariables: TResponseVariables;
|
||||
}
|
||||
): void => {
|
||||
const restoreSurveyStateFromSnapshot = (surveyState: SurveyState, snapshot: SerializedSurveyState): void => {
|
||||
if (snapshot.responseId) surveyState.updateResponseId(snapshot.responseId);
|
||||
if (snapshot.displayId) surveyState.updateDisplayId(snapshot.displayId);
|
||||
if (snapshot.userId) surveyState.updateUserId(snapshot.userId);
|
||||
if (snapshot.contactId) surveyState.updateContactId(snapshot.contactId);
|
||||
if (snapshot.singleUseId) surveyState.singleUseId = snapshot.singleUseId;
|
||||
surveyState.disableBootstrapResponseCreate();
|
||||
surveyState.responseAcc = {
|
||||
...snapshot.responseAcc,
|
||||
data: progress.responseData,
|
||||
ttc: progress.ttc,
|
||||
variables: progress.currentVariables,
|
||||
displayId: snapshot.displayId ?? snapshot.responseAcc.displayId,
|
||||
};
|
||||
surveyState.responseAcc = snapshot.responseAcc;
|
||||
};
|
||||
|
||||
interface VariableStackEntry {
|
||||
@@ -143,14 +127,6 @@ export function Survey({
|
||||
const offlinePersistEnabled =
|
||||
offlineSupport && isLinkSurvey && !isPreviewMode && !!appUrl && !!environmentId;
|
||||
|
||||
const persistSurveyStateSnapshot = useCallback(
|
||||
async (snapshotPatch: Partial<SerializedSurveyState>) => {
|
||||
if (!offlinePersistEnabled) return;
|
||||
await patchSurveyProgressSnapshot(survey.id, snapshotPatch);
|
||||
},
|
||||
[offlinePersistEnabled, survey.id]
|
||||
);
|
||||
|
||||
const responseQueue = useMemo(() => {
|
||||
if (appUrl && environmentId && surveyState) {
|
||||
return new ResponseQueue(
|
||||
@@ -184,9 +160,6 @@ export function Survey({
|
||||
setBlockId(quotaInfo.endingCardId);
|
||||
}
|
||||
},
|
||||
onResponseCreated: (responseId) => {
|
||||
void persistSurveyStateSnapshot({ responseId });
|
||||
},
|
||||
},
|
||||
surveyState
|
||||
);
|
||||
@@ -200,7 +173,6 @@ export function Survey({
|
||||
getSetIsResponseSendingFinished,
|
||||
surveyState,
|
||||
offlinePersistEnabled,
|
||||
persistSurveyStateSnapshot,
|
||||
survey.id,
|
||||
]);
|
||||
|
||||
@@ -347,7 +319,6 @@ export function Survey({
|
||||
|
||||
surveyState.updateDisplayId(display.data.id);
|
||||
responseQueue.updateSurveyState(surveyState);
|
||||
await persistSurveyStateSnapshot({ displayId: display.data.id });
|
||||
|
||||
if (onDisplayCreated) {
|
||||
onDisplayCreated();
|
||||
@@ -366,7 +337,6 @@ export function Survey({
|
||||
onDisplayCreated,
|
||||
isPreviewMode,
|
||||
onDisplay,
|
||||
persistSurveyStateSnapshot,
|
||||
]);
|
||||
|
||||
// Create display on mount. When offline persistence is enabled, wait for progress
|
||||
@@ -488,36 +458,7 @@ export function Survey({
|
||||
|
||||
// Restore survey state from snapshot
|
||||
if (surveyState && progress.surveyStateSnapshot) {
|
||||
restoreSurveyStateFromSnapshot(surveyState, progress.surveyStateSnapshot, progress);
|
||||
|
||||
if (pendingCount === 0 && !progress.surveyStateSnapshot.responseId) {
|
||||
if (progress.surveyStateSnapshot.displayId && apiClient) {
|
||||
const responseLookup = await apiClient.getResponseIdByDisplayId(
|
||||
progress.surveyStateSnapshot.displayId
|
||||
);
|
||||
|
||||
if (responseLookup.ok && responseLookup.data.responseId) {
|
||||
surveyState.updateResponseId(responseLookup.data.responseId);
|
||||
await persistSurveyStateSnapshot({ responseId: responseLookup.data.responseId });
|
||||
} else if (responseLookup.ok) {
|
||||
surveyState.enableBootstrapResponseCreate();
|
||||
} else if (responseLookup.error.status === 404) {
|
||||
surveyState.updateDisplayId(null);
|
||||
surveyState.enableBootstrapResponseCreate();
|
||||
await persistSurveyStateSnapshot({ displayId: null });
|
||||
} else {
|
||||
console.error("Formbricks: Failed to recover responseId from displayId", {
|
||||
displayId: progress.surveyStateSnapshot.displayId,
|
||||
error: responseLookup.error,
|
||||
});
|
||||
surveyState.enableBootstrapResponseCreate();
|
||||
}
|
||||
} else {
|
||||
surveyState.enableBootstrapResponseCreate();
|
||||
}
|
||||
}
|
||||
|
||||
responseQueue?.updateSurveyState(surveyState);
|
||||
restoreSurveyStateFromSnapshot(surveyState, progress.surveyStateSnapshot);
|
||||
}
|
||||
} else {
|
||||
// Block no longer exists (survey structure changed) — discard UI progress
|
||||
@@ -525,8 +466,7 @@ export function Survey({
|
||||
await clearSurveyProgress(survey.id);
|
||||
|
||||
if (surveyState && progress.surveyStateSnapshot) {
|
||||
restoreSurveyStateFromSnapshot(surveyState, progress.surveyStateSnapshot, progress);
|
||||
responseQueue?.updateSurveyState(surveyState);
|
||||
restoreSurveyStateFromSnapshot(surveyState, progress.surveyStateSnapshot);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1140,6 +1080,7 @@ export function Survey({
|
||||
languageCode={selectedLanguage}
|
||||
autoFocusEnabled={autoFocusEnabled}
|
||||
isBackButtonHidden={localSurvey.isBackButtonHidden}
|
||||
isAutoProgressingEnabled={localSurvey.isAutoProgressingEnabled}
|
||||
onOpenExternalURL={onOpenExternalURL}
|
||||
dir={dir}
|
||||
fullSizeCards={fullSizeCards}
|
||||
|
||||
@@ -46,16 +46,6 @@ export class ApiClient {
|
||||
);
|
||||
}
|
||||
|
||||
async getResponseIdByDisplayId(
|
||||
displayId: string
|
||||
): Promise<Result<{ responseId: string | null }, ApiErrorResponse>> {
|
||||
return makeRequest(
|
||||
this.appUrl,
|
||||
`/api/v1/client/${this.environmentId}/displays/${displayId}/response`,
|
||||
"GET"
|
||||
);
|
||||
}
|
||||
|
||||
async createResponse(
|
||||
responseInput: Omit<TResponseInput, "environmentId"> & {
|
||||
contactId: string | null;
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { type TSurveyElement, TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
|
||||
import {
|
||||
getAutoProgressElement,
|
||||
shouldHideSubmitButtonForAutoProgress,
|
||||
shouldTriggerAutoProgress,
|
||||
} from "./auto-progress";
|
||||
|
||||
const createElement = (id: string, type: TSurveyElementTypeEnum, required: boolean): TSurveyElement =>
|
||||
({
|
||||
id,
|
||||
type,
|
||||
required,
|
||||
}) as unknown as TSurveyElement;
|
||||
|
||||
describe("auto-progress helpers", () => {
|
||||
test("returns auto-progress element for single rating/nps blocks only", () => {
|
||||
const ratingElement = createElement("rating_1", TSurveyElementTypeEnum.Rating, true);
|
||||
const npsElement = createElement("nps_1", TSurveyElementTypeEnum.NPS, false);
|
||||
const openTextElement = createElement("text_1", TSurveyElementTypeEnum.OpenText, false);
|
||||
|
||||
expect(getAutoProgressElement([ratingElement], true)).toEqual(ratingElement);
|
||||
expect(getAutoProgressElement([npsElement], true)).toEqual(npsElement);
|
||||
expect(getAutoProgressElement([openTextElement], true)).toBeNull();
|
||||
expect(getAutoProgressElement([ratingElement], false)).toBeNull();
|
||||
expect(getAutoProgressElement([ratingElement, npsElement], true)).toBeNull();
|
||||
});
|
||||
|
||||
test("hides submit button only for required auto-progress elements", () => {
|
||||
const requiredRating = createElement("rating_required", TSurveyElementTypeEnum.Rating, true);
|
||||
const optionalRating = createElement("rating_optional", TSurveyElementTypeEnum.Rating, false);
|
||||
|
||||
expect(shouldHideSubmitButtonForAutoProgress([requiredRating], true)).toBe(true);
|
||||
expect(shouldHideSubmitButtonForAutoProgress([optionalRating], true)).toBe(false);
|
||||
expect(shouldHideSubmitButtonForAutoProgress([requiredRating], false)).toBe(false);
|
||||
});
|
||||
|
||||
test("triggers auto-progress only when an eligible response was changed", () => {
|
||||
const autoProgressElement = createElement("rating_1", TSurveyElementTypeEnum.Rating, true);
|
||||
|
||||
expect(
|
||||
shouldTriggerAutoProgress({
|
||||
changedElementId: "rating_1",
|
||||
mergedValue: { rating_1: 5 },
|
||||
autoProgressElement,
|
||||
isAlreadyInFlight: false,
|
||||
})
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
shouldTriggerAutoProgress({
|
||||
changedElementId: "other",
|
||||
mergedValue: { rating_1: 5 },
|
||||
autoProgressElement,
|
||||
isAlreadyInFlight: false,
|
||||
})
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
shouldTriggerAutoProgress({
|
||||
changedElementId: "rating_1",
|
||||
mergedValue: {},
|
||||
autoProgressElement,
|
||||
isAlreadyInFlight: false,
|
||||
})
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
shouldTriggerAutoProgress({
|
||||
changedElementId: "rating_1",
|
||||
mergedValue: { rating_1: 5 },
|
||||
autoProgressElement,
|
||||
isAlreadyInFlight: true,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { type TResponseData } from "@formbricks/types/responses";
|
||||
import { type TSurveyElement, TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
|
||||
|
||||
const isAutoProgressElementType = (type: TSurveyElementTypeEnum): boolean =>
|
||||
type === TSurveyElementTypeEnum.Rating || type === TSurveyElementTypeEnum.NPS;
|
||||
|
||||
export const getAutoProgressElement = (
|
||||
elements: TSurveyElement[],
|
||||
isAutoProgressingEnabled: boolean
|
||||
): TSurveyElement | null => {
|
||||
if (!isAutoProgressingEnabled || elements.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [element] = elements;
|
||||
return isAutoProgressElementType(element.type) ? element : null;
|
||||
};
|
||||
|
||||
export const shouldHideSubmitButtonForAutoProgress = (
|
||||
elements: TSurveyElement[],
|
||||
isAutoProgressingEnabled: boolean
|
||||
): boolean => {
|
||||
const autoProgressElement = getAutoProgressElement(elements, isAutoProgressingEnabled);
|
||||
return Boolean(autoProgressElement?.required);
|
||||
};
|
||||
|
||||
export const shouldTriggerAutoProgress = ({
|
||||
changedElementId,
|
||||
mergedValue,
|
||||
autoProgressElement,
|
||||
isAlreadyInFlight,
|
||||
}: {
|
||||
changedElementId: string;
|
||||
mergedValue: TResponseData;
|
||||
autoProgressElement: TSurveyElement | null;
|
||||
isAlreadyInFlight: boolean;
|
||||
}): boolean => {
|
||||
if (!autoProgressElement || isAlreadyInFlight || changedElementId !== autoProgressElement.id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mergedValue[autoProgressElement.id] !== undefined;
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { isValidHTML, stripInlineStyles } from "./html-utils";
|
||||
|
||||
@@ -42,6 +42,19 @@ describe("html-utils", () => {
|
||||
test("should handle empty string", () => {
|
||||
expect(stripInlineStyles("")).toBe("");
|
||||
});
|
||||
|
||||
test("should remove script tags and dangerous event handler attributes", () => {
|
||||
const input =
|
||||
'<script>alert("x")</script><img src="x" onerror="alert(1)" /><a href="https://example.com" target="_blank" onclick="alert(1)" style="color:red">Go</a>';
|
||||
const sanitized = stripInlineStyles(input);
|
||||
|
||||
expect(sanitized).not.toContain("<script");
|
||||
expect(sanitized).not.toContain("</script>");
|
||||
expect(sanitized).not.toContain("onerror=");
|
||||
expect(sanitized).not.toContain("onclick=");
|
||||
expect(sanitized).not.toContain("style=");
|
||||
expect(sanitized).toContain('target="_blank"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("isValidHTML", () => {
|
||||
|
||||
@@ -136,6 +136,7 @@ describe("Survey Logic", () => {
|
||||
displayPercentage: 0,
|
||||
recaptcha: { enabled: false, threshold: 0.5 },
|
||||
isBackButtonHidden: false,
|
||||
isAutoProgressingEnabled: false,
|
||||
segment: null,
|
||||
welcomeCard: {
|
||||
enabled: true,
|
||||
|
||||
@@ -241,44 +241,6 @@ export const getSurveyProgress = async (surveyId: string): Promise<SurveyProgres
|
||||
}
|
||||
};
|
||||
|
||||
export const patchSurveyProgressSnapshot = async (
|
||||
surveyId: string,
|
||||
snapshotPatch: Partial<SerializedSurveyState>
|
||||
): Promise<void> => {
|
||||
try {
|
||||
const db = await openDb();
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(STORE_SURVEY_PROGRESS, "readwrite");
|
||||
const store = tx.objectStore(STORE_SURVEY_PROGRESS);
|
||||
const getRequest = store.get(surveyId);
|
||||
|
||||
getRequest.onsuccess = () => {
|
||||
const existing = getRequest.result as SurveyProgressEntry | undefined;
|
||||
if (!existing) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const putRequest = store.put({
|
||||
...existing,
|
||||
surveyStateSnapshot: {
|
||||
...existing.surveyStateSnapshot,
|
||||
...snapshotPatch,
|
||||
},
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
|
||||
putRequest.onsuccess = () => resolve();
|
||||
putRequest.onerror = () => reject(putRequest.error ?? new Error("IndexedDB request failed"));
|
||||
};
|
||||
|
||||
getRequest.onerror = () => reject(getRequest.error ?? new Error("IndexedDB request failed"));
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("Formbricks: Failed to patch survey progress snapshot in IndexedDB", e);
|
||||
}
|
||||
};
|
||||
|
||||
export const clearSurveyProgress = async (surveyId: string): Promise<void> => {
|
||||
try {
|
||||
const db = await openDb();
|
||||
|
||||
@@ -20,7 +20,6 @@ interface QueueConfig {
|
||||
retryAttempts: number;
|
||||
persistOffline?: boolean;
|
||||
surveyId?: string;
|
||||
onResponseCreated?: (responseId: string) => void;
|
||||
onResponseSendingFailed?: (responseUpdate: TResponseUpdate, errorCode?: TResponseErrorCodesEnum) => void;
|
||||
onResponseSendingFinished?: () => void;
|
||||
onQuotaFull?: (quotaInfo: TQuotaFullResponse) => void;
|
||||
@@ -33,32 +32,16 @@ export const delay = (ms: number): Promise<void> => {
|
||||
});
|
||||
};
|
||||
|
||||
// Module-level locks keyed by surveyId.
|
||||
// Survive ResponseQueue instance recreation (e.g. React useMemo recomputation)
|
||||
// so that only one sync/send runs at a time per survey, even across instances.
|
||||
const syncingBySurvey = new Map<string, boolean>();
|
||||
const requestInProgressBySurvey = new Map<string, boolean>();
|
||||
|
||||
/** @internal Exposed for tests only. */
|
||||
export const _syncLocks = {
|
||||
clear: () => {
|
||||
syncingBySurvey.clear();
|
||||
requestInProgressBySurvey.clear();
|
||||
},
|
||||
set: (surveyId: string, value: boolean) => syncingBySurvey.set(surveyId, value),
|
||||
get: (surveyId: string) => syncingBySurvey.get(surveyId) ?? false,
|
||||
setRequestInProgress: (surveyId: string, value: boolean) => requestInProgressBySurvey.set(surveyId, value),
|
||||
getRequestInProgress: (surveyId: string) => requestInProgressBySurvey.get(surveyId) ?? false,
|
||||
};
|
||||
|
||||
export class ResponseQueue {
|
||||
readonly queue: TResponseUpdate[] = [];
|
||||
readonly config: QueueConfig;
|
||||
private surveyState: SurveyState;
|
||||
private isRequestInProgress = false;
|
||||
readonly api: ApiClient;
|
||||
private responseRecaptchaToken?: string;
|
||||
// Maps in-memory queue index → IndexedDB id for cleanup after successful send
|
||||
private readonly pendingDbIds: Map<TResponseUpdate, number> = new Map();
|
||||
private isSyncing = false;
|
||||
|
||||
constructor(config: QueueConfig, surveyState: SurveyState) {
|
||||
this.config = config;
|
||||
@@ -69,26 +52,6 @@ export class ResponseQueue {
|
||||
});
|
||||
}
|
||||
|
||||
private get isSyncing(): boolean {
|
||||
return this.config.surveyId ? (syncingBySurvey.get(this.config.surveyId) ?? false) : false;
|
||||
}
|
||||
|
||||
private set isSyncing(value: boolean) {
|
||||
if (this.config.surveyId) {
|
||||
syncingBySurvey.set(this.config.surveyId, value);
|
||||
}
|
||||
}
|
||||
|
||||
private get isRequestInProgress(): boolean {
|
||||
return this.config.surveyId ? (requestInProgressBySurvey.get(this.config.surveyId) ?? false) : false;
|
||||
}
|
||||
|
||||
private set isRequestInProgress(value: boolean) {
|
||||
if (this.config.surveyId) {
|
||||
requestInProgressBySurvey.set(this.config.surveyId, value);
|
||||
}
|
||||
}
|
||||
|
||||
setResponseRecaptchaToken(token?: string) {
|
||||
this.responseRecaptchaToken = token;
|
||||
}
|
||||
@@ -148,26 +111,8 @@ export class ResponseQueue {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
// When offline support is active and there are multiple pending entries in
|
||||
// IndexedDB, defer to syncPersistedResponses which drains them in order.
|
||||
// This prevents processQueue and syncPersistedResponses from racing to
|
||||
// create the same response concurrently (duplicate POSTs).
|
||||
if (this.config.persistOffline && this.config.surveyId) {
|
||||
const pendingCount = await countPendingResponses(this.config.surveyId);
|
||||
|
||||
// Re-check after await — another processQueue/sync may have started during the yield
|
||||
if (this.isSyncing || this.isRequestInProgress || this.queue.length === 0) {
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
if (pendingCount > 1) {
|
||||
void this.syncPersistedResponses();
|
||||
return { success: false };
|
||||
}
|
||||
}
|
||||
|
||||
const responseUpdate = this.queue[0];
|
||||
this.isRequestInProgress = true;
|
||||
const responseUpdate = this.queue[0];
|
||||
|
||||
const result = await this.sendResponseWithRetry(responseUpdate);
|
||||
|
||||
@@ -224,11 +169,6 @@ export class ResponseQueue {
|
||||
|
||||
// Concurrency guard: prevent duplicate syncs from online/offline flicker
|
||||
if (this.isSyncing) return { success: false, syncedCount: 0 };
|
||||
|
||||
// If processQueue already has a request in flight, don't start syncing —
|
||||
// let it finish first to avoid both paths creating the same response.
|
||||
if (this.isRequestInProgress) return { success: false, syncedCount: 0 };
|
||||
|
||||
this.isSyncing = true;
|
||||
|
||||
try {
|
||||
@@ -360,37 +300,6 @@ export class ResponseQueue {
|
||||
return error.details?.code === RECAPTCHA_VERIFICATION_ERROR_CODE;
|
||||
}
|
||||
|
||||
private getCreatePayload(
|
||||
responseUpdate: TResponseUpdate
|
||||
): Omit<
|
||||
Parameters<ApiClient["createResponse"]>[0],
|
||||
"contactId" | "userId" | "singleUseId" | "surveyId" | "displayId" | "recaptchaToken"
|
||||
> {
|
||||
if (!this.surveyState.shouldCreateResponseFromState) {
|
||||
return {
|
||||
finished: responseUpdate.finished,
|
||||
data: { ...responseUpdate.data, ...responseUpdate.hiddenFields },
|
||||
ttc: responseUpdate.ttc,
|
||||
variables: responseUpdate.variables,
|
||||
language: responseUpdate.language,
|
||||
meta: responseUpdate.meta,
|
||||
endingId: responseUpdate.endingId,
|
||||
};
|
||||
}
|
||||
|
||||
const accumulatedResponse = this.surveyState.responseAcc;
|
||||
|
||||
return {
|
||||
finished: accumulatedResponse.finished,
|
||||
data: { ...accumulatedResponse.data, ...responseUpdate.hiddenFields },
|
||||
ttc: accumulatedResponse.ttc,
|
||||
variables: accumulatedResponse.variables,
|
||||
language: accumulatedResponse.language ?? responseUpdate.language,
|
||||
meta: accumulatedResponse.meta ?? responseUpdate.meta,
|
||||
endingId: accumulatedResponse.endingId ?? responseUpdate.endingId,
|
||||
};
|
||||
}
|
||||
|
||||
private handleSuccessfulResponse(responseUpdate: TResponseUpdate, quotaFullResponse?: TQuotaFullResponse) {
|
||||
if (responseUpdate.finished) {
|
||||
this.config.onResponseSendingFinished?.();
|
||||
@@ -431,13 +340,13 @@ export class ResponseQueue {
|
||||
return err(response.error);
|
||||
}
|
||||
} else {
|
||||
const createPayload = this.getCreatePayload(responseUpdate);
|
||||
response = await this.api.createResponse({
|
||||
...createPayload,
|
||||
...responseUpdate,
|
||||
surveyId: this.surveyState.surveyId,
|
||||
contactId: this.surveyState.contactId || null,
|
||||
userId: this.surveyState.userId || null,
|
||||
singleUseId: this.surveyState.singleUseId || null,
|
||||
data: { ...responseUpdate.data, ...responseUpdate.hiddenFields },
|
||||
displayId: this.surveyState.displayId,
|
||||
recaptchaToken: this.responseRecaptchaToken ?? undefined,
|
||||
});
|
||||
@@ -447,8 +356,6 @@ export class ResponseQueue {
|
||||
}
|
||||
|
||||
this.surveyState.updateResponseId(response.data.id);
|
||||
this.surveyState.disableBootstrapResponseCreate();
|
||||
this.config.onResponseCreated?.(response.data.id);
|
||||
if (this.config.setSurveyState) {
|
||||
this.config.setSurveyState(this.surveyState);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment happy-dom
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { err, ok } from "@formbricks/types/error-handlers";
|
||||
import { TResponseUpdate } from "@formbricks/types/responses";
|
||||
import { TResponseErrorCodesEnum } from "@/types/response-error-codes";
|
||||
import { ResponseQueue, _syncLocks, delay } from "./response-queue";
|
||||
import { ResponseQueue, delay } from "./response-queue";
|
||||
import { SurveyState } from "./survey-state";
|
||||
|
||||
// Suppress noisy console output from retry logic during tests
|
||||
@@ -38,14 +38,11 @@ const getSurveyState: () => SurveyState = () => ({
|
||||
contactId: "contact1",
|
||||
surveyId: "survey1",
|
||||
singleUseId: "single1",
|
||||
shouldCreateResponseFromState: false,
|
||||
responseAcc: { finished: false, data: {}, ttc: {}, variables: {} },
|
||||
updateResponseId: vi.fn(),
|
||||
updateDisplayId: vi.fn(),
|
||||
updateUserId: vi.fn(),
|
||||
updateContactId: vi.fn(),
|
||||
enableBootstrapResponseCreate: vi.fn(),
|
||||
disableBootstrapResponseCreate: vi.fn(),
|
||||
accumulateResponse: vi.fn(),
|
||||
isResponseFinished: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
@@ -89,7 +86,6 @@ describe("ResponseQueue", () => {
|
||||
queue = new ResponseQueue(config, surveyState);
|
||||
apiMock = queue.api;
|
||||
vi.clearAllMocks();
|
||||
_syncLocks.clear();
|
||||
});
|
||||
|
||||
test("constructor initializes properties", () => {
|
||||
@@ -114,30 +110,26 @@ describe("ResponseQueue", () => {
|
||||
});
|
||||
|
||||
test("processQueue does nothing if request in progress or queue empty", async () => {
|
||||
const reqQueue = new ResponseQueue(getConfig({ surveyId: "s1" }), getSurveyState());
|
||||
_syncLocks.setRequestInProgress("s1", true);
|
||||
await reqQueue.processQueue();
|
||||
_syncLocks.setRequestInProgress("s1", false);
|
||||
reqQueue.queue.length = 0;
|
||||
await reqQueue.processQueue();
|
||||
queue["isRequestInProgress"] = true;
|
||||
await queue.processQueue();
|
||||
queue["isRequestInProgress"] = false;
|
||||
queue.queue.length = 0;
|
||||
await queue.processQueue();
|
||||
expect(true).toBe(true); // just to ensure no errors
|
||||
});
|
||||
|
||||
test("processQueue sends response and removes from queue on success", async () => {
|
||||
const reqQueue = new ResponseQueue(getConfig({ surveyId: "s1" }), getSurveyState());
|
||||
reqQueue.queue.push(responseUpdate);
|
||||
vi.spyOn(reqQueue, "sendResponse").mockResolvedValue(ok(true));
|
||||
await reqQueue.processQueue();
|
||||
expect(reqQueue.queue.length).toBe(0);
|
||||
expect(_syncLocks.getRequestInProgress("s1")).toBe(false);
|
||||
queue.queue.push(responseUpdate);
|
||||
vi.spyOn(queue, "sendResponse").mockResolvedValue(ok(true));
|
||||
await queue.processQueue();
|
||||
expect(queue.queue.length).toBe(0);
|
||||
expect(queue["isRequestInProgress"]).toBe(false);
|
||||
});
|
||||
|
||||
test("processQueue retries and calls onResponseSendingFailed on recaptcha error", async () => {
|
||||
const recaptchaConfig = getConfig({ surveyId: "s1" });
|
||||
const recaptchaQueue = new ResponseQueue(recaptchaConfig, getSurveyState());
|
||||
recaptchaQueue.queue.push(responseUpdate);
|
||||
queue.queue.push(responseUpdate);
|
||||
|
||||
vi.spyOn(recaptchaQueue, "sendResponse").mockResolvedValue(
|
||||
vi.spyOn(queue, "sendResponse").mockResolvedValue(
|
||||
err({
|
||||
code: "internal_server_error",
|
||||
message: "An error occurred while sending the response.",
|
||||
@@ -147,31 +139,29 @@ describe("ResponseQueue", () => {
|
||||
},
|
||||
})
|
||||
);
|
||||
await recaptchaQueue.processQueue();
|
||||
expect(recaptchaConfig.onResponseSendingFailed).toHaveBeenCalledWith(
|
||||
await queue.processQueue();
|
||||
expect(config.onResponseSendingFailed).toHaveBeenCalledWith(
|
||||
responseUpdate,
|
||||
TResponseErrorCodesEnum.RecaptchaError
|
||||
);
|
||||
expect(_syncLocks.getRequestInProgress("s1")).toBe(false);
|
||||
expect(queue["isRequestInProgress"]).toBe(false);
|
||||
});
|
||||
|
||||
test("processQueue retries and calls onResponseSendingFailed after max attempts", async () => {
|
||||
const reqConfig = getConfig({ surveyId: "s1" });
|
||||
const reqQueue = new ResponseQueue(reqConfig, getSurveyState());
|
||||
reqQueue.queue.push(responseUpdate);
|
||||
vi.spyOn(reqQueue, "sendResponse").mockResolvedValue(
|
||||
queue.queue.push(responseUpdate);
|
||||
vi.spyOn(queue, "sendResponse").mockResolvedValue(
|
||||
err({
|
||||
code: "internal_server_error",
|
||||
message: "An error occurred while sending the response.",
|
||||
status: 500,
|
||||
})
|
||||
);
|
||||
await reqQueue.processQueue();
|
||||
expect(reqConfig.onResponseSendingFailed).toHaveBeenCalledWith(
|
||||
await queue.processQueue();
|
||||
expect(config.onResponseSendingFailed).toHaveBeenCalledWith(
|
||||
responseUpdate,
|
||||
TResponseErrorCodesEnum.ResponseSendingError
|
||||
);
|
||||
expect(_syncLocks.getRequestInProgress("s1")).toBe(false);
|
||||
expect(queue["isRequestInProgress"]).toBe(false);
|
||||
});
|
||||
|
||||
test("processQueue calls onResponseSendingFinished if finished", async () => {
|
||||
@@ -194,7 +184,6 @@ describe("ResponseQueue", () => {
|
||||
const result = await queue.sendResponse(responseUpdate);
|
||||
expect(apiMock.createResponse).toHaveBeenCalled();
|
||||
expect(surveyState.updateResponseId).toHaveBeenCalledWith("newid");
|
||||
expect(surveyState.disableBootstrapResponseCreate).toHaveBeenCalled();
|
||||
expect(config.setSurveyState).toHaveBeenCalledWith(surveyState);
|
||||
expect(result.ok).toBe(true);
|
||||
});
|
||||
@@ -229,9 +218,8 @@ describe("ResponseQueue", () => {
|
||||
});
|
||||
|
||||
test("processQueueAsync returns success false if request in progress", async () => {
|
||||
const reqQueue = new ResponseQueue(getConfig({ surveyId: "s1" }), getSurveyState());
|
||||
_syncLocks.setRequestInProgress("s1", true);
|
||||
const result = await reqQueue.processQueue();
|
||||
queue["isRequestInProgress"] = true;
|
||||
const result = await queue.processQueue();
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
@@ -321,13 +309,9 @@ describe("ResponseQueue", () => {
|
||||
});
|
||||
|
||||
test("processQueue returns false when isSyncing is true", async () => {
|
||||
const offlineQueue = new ResponseQueue(
|
||||
getConfig({ persistOffline: true, surveyId: "s1" }),
|
||||
getSurveyState()
|
||||
);
|
||||
offlineQueue.queue.push(responseUpdate);
|
||||
_syncLocks.set("s1", true);
|
||||
const result = await offlineQueue.processQueue();
|
||||
queue.queue.push(responseUpdate);
|
||||
queue["isSyncing"] = true;
|
||||
const result = await queue.processQueue();
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
@@ -363,7 +347,7 @@ describe("ResponseQueue", () => {
|
||||
getConfig({ persistOffline: true, surveyId: "s1" }),
|
||||
getSurveyState()
|
||||
);
|
||||
_syncLocks.set("s1", true);
|
||||
offlineQueue["isSyncing"] = true;
|
||||
const result = await offlineQueue.syncPersistedResponses();
|
||||
expect(result).toEqual({ success: false, syncedCount: 0 });
|
||||
});
|
||||
@@ -398,7 +382,7 @@ describe("ResponseQueue", () => {
|
||||
expect(result).toEqual({ success: true, syncedCount: 1 });
|
||||
expect(removePendingResponse).toHaveBeenCalledWith(10);
|
||||
expect(offlineQueue.queue.length).toBe(0);
|
||||
expect(_syncLocks.get("s1")).toBe(false);
|
||||
expect(offlineQueue["isSyncing"]).toBe(false);
|
||||
});
|
||||
|
||||
test("syncPersistedResponses stops on server error", async () => {
|
||||
@@ -431,7 +415,7 @@ describe("ResponseQueue", () => {
|
||||
|
||||
const result = await offlineQueue.syncPersistedResponses();
|
||||
expect(result).toEqual({ success: false, syncedCount: 0 });
|
||||
expect(_syncLocks.get("s1")).toBe(false);
|
||||
expect(offlineQueue["isSyncing"]).toBe(false);
|
||||
});
|
||||
|
||||
test("syncPersistedResponses retries 404 as createResponse by resetting responseId", async () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { type TProjectStyling } from "@formbricks/types/project";
|
||||
import { type TSurveyStyling } from "@formbricks/types/surveys/types";
|
||||
|
||||
@@ -14,7 +14,6 @@ describe("SurveyState", () => {
|
||||
expect(surveyState.surveyId).toBe(initialSurveyId);
|
||||
expect(surveyState.responseId).toBeNull();
|
||||
expect(surveyState.displayId).toBeNull();
|
||||
expect(surveyState.shouldCreateResponseFromState).toBe(false);
|
||||
expect(surveyState.userId).toBeNull();
|
||||
expect(surveyState.contactId).toBeNull();
|
||||
expect(surveyState.singleUseId).toBeNull();
|
||||
@@ -138,7 +137,7 @@ describe("SurveyState", () => {
|
||||
|
||||
expect(surveyState.responseAcc.finished).toBe(true);
|
||||
expect(surveyState.responseAcc.data).toEqual({ q1: "newAns1", q2: "ans2" });
|
||||
expect(surveyState.responseAcc.ttc).toEqual({ q1: 100, q2: 200 });
|
||||
expect(surveyState.responseAcc.ttc).toEqual({ q2: 200 }); // ttc is overwritten
|
||||
expect(surveyState.responseAcc.variables).toEqual({ varB: "valB" }); // variables are overwritten
|
||||
expect(surveyState.responseAcc.displayId).toBe("display123");
|
||||
});
|
||||
@@ -159,11 +158,9 @@ describe("SurveyState", () => {
|
||||
describe("clear", () => {
|
||||
test("should reset responseId and responseAcc", () => {
|
||||
surveyState.responseId = "someId";
|
||||
surveyState.enableBootstrapResponseCreate();
|
||||
surveyState.responseAcc = { finished: true, data: { q: "a" }, ttc: { q: 1 }, variables: { v: "1" } };
|
||||
surveyState.clear();
|
||||
expect(surveyState.responseId).toBeNull();
|
||||
expect(surveyState.shouldCreateResponseFromState).toBe(false);
|
||||
expect(surveyState.responseAcc).toEqual({ finished: false, data: {}, ttc: {}, variables: {} });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,6 @@ export class SurveyState {
|
||||
userId: string | null = null;
|
||||
contactId: string | null = null;
|
||||
surveyId: string;
|
||||
shouldCreateResponseFromState = false;
|
||||
responseAcc: TResponseUpdate = { finished: false, data: {}, ttc: {}, variables: {} };
|
||||
singleUseId: string | null;
|
||||
|
||||
@@ -60,7 +59,7 @@ export class SurveyState {
|
||||
* Update the display ID after a successful display creation
|
||||
* @param id - The display ID
|
||||
*/
|
||||
updateDisplayId(id: string | null) {
|
||||
updateDisplayId(id: string) {
|
||||
this.displayId = id;
|
||||
}
|
||||
|
||||
@@ -80,14 +79,6 @@ export class SurveyState {
|
||||
this.contactId = id;
|
||||
}
|
||||
|
||||
enableBootstrapResponseCreate() {
|
||||
this.shouldCreateResponseFromState = true;
|
||||
}
|
||||
|
||||
disableBootstrapResponseCreate() {
|
||||
this.shouldCreateResponseFromState = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulate the responses
|
||||
* @param responseUpdate - The new response data to add
|
||||
@@ -95,14 +86,10 @@ export class SurveyState {
|
||||
accumulateResponse(responseUpdate: TResponseUpdate) {
|
||||
this.responseAcc = {
|
||||
finished: responseUpdate.finished,
|
||||
ttc: { ...this.responseAcc.ttc, ...responseUpdate.ttc },
|
||||
ttc: responseUpdate.ttc,
|
||||
data: { ...this.responseAcc.data, ...responseUpdate.data },
|
||||
variables: responseUpdate.variables ?? this.responseAcc.variables,
|
||||
displayId: responseUpdate.displayId ?? this.responseAcc.displayId,
|
||||
language: responseUpdate.language ?? this.responseAcc.language,
|
||||
meta: responseUpdate.meta ?? this.responseAcc.meta,
|
||||
hiddenFields: responseUpdate.hiddenFields ?? this.responseAcc.hiddenFields,
|
||||
endingId: responseUpdate.endingId,
|
||||
variables: responseUpdate.variables,
|
||||
displayId: responseUpdate.displayId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -118,7 +105,6 @@ export class SurveyState {
|
||||
*/
|
||||
clear() {
|
||||
this.responseId = null;
|
||||
this.shouldCreateResponseFromState = false;
|
||||
this.responseAcc = { finished: false, data: {}, ttc: {}, variables: {} };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment happy-dom
|
||||
import { act, renderHook } from "@testing-library/preact";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import type { TResponseTtc } from "@formbricks/types/responses";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// @vitest-environment jsdom
|
||||
// @vitest-environment happy-dom
|
||||
import { act, renderHook } from "@testing-library/preact";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { useOnlineStatus } from "./use-online-status";
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { TJsEnvironmentStateSurvey } from "../../../types/js";
|
||||
import { type TAllowedFileExtension, mimeTypes } from "../../../types/storage";
|
||||
import type { TSurveyLanguage } from "../../../types/surveys/types";
|
||||
import {
|
||||
cn,
|
||||
findBlockByElementId,
|
||||
getDefaultLanguageCode,
|
||||
getElementsFromSurveyBlocks,
|
||||
@@ -510,3 +511,45 @@ describe("isRTLLanguage", () => {
|
||||
expect(isRTLLanguage(survey, "default")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cn", () => {
|
||||
test("joins multiple classes", () => {
|
||||
expect(cn("foo", "bar")).toBe("foo bar");
|
||||
});
|
||||
|
||||
test("filters out undefined values", () => {
|
||||
expect(cn("foo", undefined, "bar")).toBe("foo bar");
|
||||
});
|
||||
|
||||
test("filters out empty strings", () => {
|
||||
expect(cn("foo", "", "bar")).toBe("foo bar");
|
||||
});
|
||||
|
||||
test("merges conflicting tailwind classes (last wins)", () => {
|
||||
expect(cn("mb-6", "mb-8")).toBe("mb-8");
|
||||
});
|
||||
|
||||
test("merges conflicting min-h classes", () => {
|
||||
expect(cn("min-h-40", "min-h-0")).toBe("min-h-0");
|
||||
});
|
||||
|
||||
test("merges conflicting padding classes", () => {
|
||||
expect(cn("p-4", "p-2")).toBe("p-2");
|
||||
});
|
||||
|
||||
test("keeps non-conflicting classes", () => {
|
||||
expect(cn("mb-6 block rounded-md", "w-1/4")).toBe("mb-6 block rounded-md w-1/4");
|
||||
});
|
||||
|
||||
test("handles single class", () => {
|
||||
expect(cn("foo")).toBe("foo");
|
||||
});
|
||||
|
||||
test("handles no arguments", () => {
|
||||
expect(cn()).toBe("");
|
||||
});
|
||||
|
||||
test("handles all undefined", () => {
|
||||
expect(cn(undefined, undefined)).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -88,6 +88,46 @@ describe("validateElementResponse", () => {
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
test("should return error when required multi-select has other selected but no text", () => {
|
||||
const element = {
|
||||
id: "mc1",
|
||||
type: TSurveyElementTypeEnum.MultipleChoiceMulti,
|
||||
headline: { default: "Pick" },
|
||||
required: true,
|
||||
choices: [{ id: "opt1", label: { default: "Option 1" } }],
|
||||
} as unknown as TSurveyElement;
|
||||
|
||||
const result = validateElementResponse(element, ["opt1", ""], "en");
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors[0].ruleId).toBe("required");
|
||||
});
|
||||
|
||||
test("should return valid when required multi-select has other with text (legacy sentinel)", () => {
|
||||
const element = {
|
||||
id: "mc1",
|
||||
type: TSurveyElementTypeEnum.MultipleChoiceMulti,
|
||||
headline: { default: "Pick" },
|
||||
required: true,
|
||||
choices: [{ id: "opt1", label: { default: "Option 1" } }],
|
||||
} as unknown as TSurveyElement;
|
||||
|
||||
const result = validateElementResponse(element, ["opt1", "", "custom"], "en");
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
test("should return valid when required multi-select has other text without sentinel", () => {
|
||||
const element = {
|
||||
id: "mc1",
|
||||
type: TSurveyElementTypeEnum.MultipleChoiceMulti,
|
||||
headline: { default: "Pick" },
|
||||
required: true,
|
||||
choices: [{ id: "opt1", label: { default: "Option 1" } }],
|
||||
} as unknown as TSurveyElement;
|
||||
|
||||
const result = validateElementResponse(element, ["opt1", "custom"], "en");
|
||||
expect(result.valid).toBe(true);
|
||||
});
|
||||
|
||||
test("should handle required ranking element - at least one ranked", () => {
|
||||
const element: TSurveyElement = {
|
||||
id: "rank1",
|
||||
|
||||
@@ -29,6 +29,7 @@ export const ZJsEnvironmentStateSurvey = ZSurveyBase.pick({
|
||||
delay: true,
|
||||
projectOverwrites: true,
|
||||
isBackButtonHidden: true,
|
||||
isAutoProgressingEnabled: true,
|
||||
recaptcha: true,
|
||||
}).superRefine((survey, ctx) => {
|
||||
surveyRefinement(survey as z.infer<typeof ZSurveyBase>, ctx);
|
||||
|
||||
@@ -914,6 +914,7 @@ export const ZSurveyBase = z.object({
|
||||
recaptcha: ZSurveyRecaptcha.nullable(),
|
||||
isSingleResponsePerEmailEnabled: z.boolean(),
|
||||
isBackButtonHidden: z.boolean(),
|
||||
isAutoProgressingEnabled: z.boolean().optional().prefault(false),
|
||||
isCaptureIpEnabled: z.boolean(),
|
||||
pin: z
|
||||
.string()
|
||||
@@ -3798,6 +3799,7 @@ export const ZSurveyCreateInput = makeSchemaOptional(ZSurveyBase)
|
||||
endings: ZSurveyEndings.prefault([]),
|
||||
type: ZSurveyType.prefault("link"),
|
||||
followUps: z.array(ZSurveyFollowUp.omit({ createdAt: true, updatedAt: true })).prefault([]),
|
||||
isAutoProgressingEnabled: z.boolean().prefault(false),
|
||||
})
|
||||
.superRefine((survey, ctx) => {
|
||||
surveyRefinement(survey as z.infer<typeof ZSurveyBase>, ctx);
|
||||
@@ -3846,6 +3848,7 @@ export const ZSurveyCreateInputWithEnvironmentId = makeSchemaOptional(ZSurveyBas
|
||||
endings: ZSurveyEndings.prefault([]),
|
||||
type: ZSurveyType.prefault("link"),
|
||||
followUps: z.array(ZSurveyFollowUp.omit({ createdAt: true, updatedAt: true })).prefault([]),
|
||||
isAutoProgressingEnabled: z.boolean().prefault(false),
|
||||
})
|
||||
.superRefine((survey, ctx) => {
|
||||
surveyRefinement(survey as z.infer<typeof ZSurveyBase>, ctx);
|
||||
|
||||
Generated
+59
-28
@@ -495,7 +495,7 @@ importers:
|
||||
version: 1.2.0
|
||||
'@vitest/coverage-v8':
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
autoprefixer:
|
||||
specifier: 10.4.27
|
||||
version: 10.4.27(postcss@8.5.8)
|
||||
@@ -519,10 +519,10 @@ importers:
|
||||
version: 6.1.1(typescript@5.9.3)(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
vitest-mock-extended:
|
||||
specifier: 3.1.0
|
||||
version: 3.1.0(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 3.1.0(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
|
||||
packages/ai:
|
||||
dependencies:
|
||||
@@ -556,7 +556,7 @@ importers:
|
||||
version: link:../config-eslint
|
||||
'@vitest/coverage-v8':
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vite:
|
||||
specifier: 8.0.0
|
||||
version: 8.0.0(@emnapi/core@1.7.1)(@emnapi/runtime@1.8.1)(@types/node@25.4.0)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
@@ -565,7 +565,7 @@ importers:
|
||||
version: 4.5.4(@types/node@25.4.0)(rollup@4.59.0)(typescript@5.9.3)(vite@8.0.0(@emnapi/core@1.7.1)(@emnapi/runtime@1.8.1)(@types/node@25.4.0)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/cache:
|
||||
dependencies:
|
||||
@@ -587,13 +587,13 @@ importers:
|
||||
version: link:../config-eslint
|
||||
'@vitest/coverage-v8':
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vite:
|
||||
specifier: 7.3.1
|
||||
version: 7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/config-eslint:
|
||||
devDependencies:
|
||||
@@ -608,10 +608,10 @@ importers:
|
||||
version: 8.57.0(eslint@8.57.1)(typescript@5.9.3)
|
||||
'@vercel/style-guide':
|
||||
specifier: 6.0.0
|
||||
version: 6.0.0(@next/eslint-plugin-next@15.5.12)(eslint@8.57.1)(prettier@3.8.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 6.0.0(@next/eslint-plugin-next@15.5.12)(eslint@8.57.1)(prettier@3.8.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
'@vitest/eslint-plugin':
|
||||
specifier: 1.6.10
|
||||
version: 1.6.10(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 1.6.10(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
eslint-config-next:
|
||||
specifier: 15.5.12
|
||||
version: 15.5.12(eslint@8.57.1)(typescript@5.9.3)
|
||||
@@ -776,7 +776,7 @@ importers:
|
||||
version: 4.5.4(@types/node@25.4.0)(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/js-core:
|
||||
devDependencies:
|
||||
@@ -788,7 +788,7 @@ importers:
|
||||
version: link:../config-eslint
|
||||
'@vitest/coverage-v8':
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
terser:
|
||||
specifier: 5.46.0
|
||||
version: 5.46.0
|
||||
@@ -800,7 +800,7 @@ importers:
|
||||
version: 4.5.4(@types/node@25.4.0)(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/logger:
|
||||
dependencies:
|
||||
@@ -831,7 +831,7 @@ importers:
|
||||
version: 4.5.4(@types/node@25.4.0)(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/storage:
|
||||
dependencies:
|
||||
@@ -856,7 +856,7 @@ importers:
|
||||
version: link:../config-eslint
|
||||
'@vitest/coverage-v8':
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vite:
|
||||
specifier: 7.3.1
|
||||
version: 7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
@@ -865,7 +865,7 @@ importers:
|
||||
version: 4.5.4(@types/node@25.4.0)(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/survey-ui:
|
||||
dependencies:
|
||||
@@ -941,7 +941,7 @@ importers:
|
||||
version: 5.1.4(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
'@vitest/coverage-v8':
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
version: 4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
react:
|
||||
specifier: 19.2.4
|
||||
version: 19.2.4
|
||||
@@ -965,7 +965,7 @@ importers:
|
||||
version: 6.1.1(typescript@5.9.3)(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
vitest:
|
||||
specifier: 4.0.18
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
version: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
packages/surveys:
|
||||
dependencies:
|
||||
@@ -1027,6 +1027,9 @@ importers:
|
||||
fake-indexeddb:
|
||||
specifier: 6.2.5
|
||||
version: 6.2.5
|
||||
happy-dom:
|
||||
specifier: 20.8.9
|
||||
version: 20.8.9
|
||||
postcss:
|
||||
specifier: 8.5.8
|
||||
version: 8.5.8
|
||||
@@ -5763,6 +5766,9 @@ packages:
|
||||
'@types/webidl-conversions@7.0.3':
|
||||
resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}
|
||||
|
||||
'@types/whatwg-mimetype@3.0.2':
|
||||
resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
|
||||
|
||||
'@types/whatwg-url@11.0.5':
|
||||
resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==}
|
||||
|
||||
@@ -7955,6 +7961,10 @@ packages:
|
||||
resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
happy-dom@20.8.9:
|
||||
resolution: {integrity: sha512-Tz23LR9T9jOGVZm2x1EPdXqwA37G/owYMxRwU0E4miurAtFsPMQ1d2Jc2okUaSjZqAFz2oEn3FLXC5a0a+siyA==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
has-bigints@1.1.0:
|
||||
resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -11280,6 +11290,10 @@ packages:
|
||||
webpack-cli:
|
||||
optional: true
|
||||
|
||||
whatwg-mimetype@3.0.0:
|
||||
resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
whatwg-mimetype@5.0.0:
|
||||
resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}
|
||||
engines: {node: '>=20'}
|
||||
@@ -17878,6 +17892,8 @@ snapshots:
|
||||
|
||||
'@types/webidl-conversions@7.0.3': {}
|
||||
|
||||
'@types/whatwg-mimetype@3.0.2': {}
|
||||
|
||||
'@types/whatwg-url@11.0.5':
|
||||
dependencies:
|
||||
'@types/webidl-conversions': 7.0.3
|
||||
@@ -18221,7 +18237,7 @@ snapshots:
|
||||
|
||||
'@vercel/oidc@3.1.0': {}
|
||||
|
||||
'@vercel/style-guide@6.0.0(@next/eslint-plugin-next@15.5.12)(eslint@8.57.1)(prettier@3.8.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
'@vercel/style-guide@6.0.0(@next/eslint-plugin-next@15.5.12)(eslint@8.57.1)(prettier@3.8.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
dependencies:
|
||||
'@babel/core': 7.28.5
|
||||
'@babel/eslint-parser': 7.28.5(@babel/core@7.28.5)(eslint@8.57.1)
|
||||
@@ -18241,7 +18257,7 @@ snapshots:
|
||||
eslint-plugin-testing-library: 6.5.0(eslint@8.57.1)(typescript@5.9.3)
|
||||
eslint-plugin-tsdoc: 0.2.17
|
||||
eslint-plugin-unicorn: 51.0.1(eslint@8.57.1)
|
||||
eslint-plugin-vitest: 0.3.26(@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
eslint-plugin-vitest: 0.3.26(@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
prettier-plugin-packagejson: 2.5.20(prettier@3.8.1)
|
||||
optionalDependencies:
|
||||
'@next/eslint-plugin-next': 15.5.12
|
||||
@@ -18267,7 +18283,7 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@vitest/coverage-v8@4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
'@vitest/coverage-v8@4.0.18(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
dependencies:
|
||||
'@bcoe/v8-coverage': 1.0.2
|
||||
'@vitest/utils': 4.0.18
|
||||
@@ -18279,16 +18295,16 @@ snapshots:
|
||||
obug: 2.1.1
|
||||
std-env: 3.10.0
|
||||
tinyrainbow: 3.0.3
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
'@vitest/eslint-plugin@1.6.10(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
'@vitest/eslint-plugin@1.6.10(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 8.56.1
|
||||
'@typescript-eslint/utils': 8.56.1(eslint@8.57.1)(typescript@5.9.3)
|
||||
eslint: 8.57.1
|
||||
optionalDependencies:
|
||||
typescript: 5.9.3
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -19928,13 +19944,13 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
eslint-plugin-vitest@0.3.26(@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)):
|
||||
eslint-plugin-vitest@0.3.26(@typescript-eslint/eslint-plugin@7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)):
|
||||
dependencies:
|
||||
'@typescript-eslint/utils': 7.18.0(eslint@8.57.1)(typescript@5.9.3)
|
||||
eslint: 8.57.1
|
||||
optionalDependencies:
|
||||
'@typescript-eslint/eslint-plugin': 7.18.0(@typescript-eslint/parser@7.18.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1)(typescript@5.9.3)
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
- typescript
|
||||
@@ -20468,6 +20484,18 @@ snapshots:
|
||||
- encoding
|
||||
- supports-color
|
||||
|
||||
happy-dom@20.8.9:
|
||||
dependencies:
|
||||
'@types/node': 25.4.0
|
||||
'@types/whatwg-mimetype': 3.0.2
|
||||
'@types/ws': 8.18.1
|
||||
entities: 7.0.1
|
||||
whatwg-mimetype: 3.0.0
|
||||
ws: 8.18.3
|
||||
transitivePeerDependencies:
|
||||
- bufferutil
|
||||
- utf-8-validate
|
||||
|
||||
has-bigints@1.1.0: {}
|
||||
|
||||
has-flag@4.0.0: {}
|
||||
@@ -23901,13 +23929,13 @@ snapshots:
|
||||
- '@emnapi/core'
|
||||
- '@emnapi/runtime'
|
||||
|
||||
vitest-mock-extended@3.1.0(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)):
|
||||
vitest-mock-extended@3.1.0(typescript@5.9.3)(vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)):
|
||||
dependencies:
|
||||
ts-essentials: 10.1.1(typescript@5.9.3)
|
||||
typescript: 5.9.3
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
vitest: 4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
|
||||
|
||||
vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2):
|
||||
vitest@4.0.18(@opentelemetry/api@1.9.0)(@types/node@25.4.0)(happy-dom@20.8.9)(jiti@2.6.1)(jsdom@28.1.0(@noble/hashes@2.0.1))(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.0.18
|
||||
'@vitest/mocker': 4.0.18(vite@7.3.1(@types/node@25.4.0)(jiti@2.6.1)(lightningcss@1.32.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))
|
||||
@@ -23932,6 +23960,7 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@types/node': 25.4.0
|
||||
happy-dom: 20.8.9
|
||||
jsdom: 28.1.0(@noble/hashes@2.0.1)
|
||||
transitivePeerDependencies:
|
||||
- jiti
|
||||
@@ -24042,6 +24071,8 @@ snapshots:
|
||||
- uglify-js
|
||||
optional: true
|
||||
|
||||
whatwg-mimetype@3.0.0: {}
|
||||
|
||||
whatwg-mimetype@5.0.0: {}
|
||||
|
||||
whatwg-url@14.2.0:
|
||||
|
||||
Reference in New Issue
Block a user