Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(surveys): isolate hosted survey content (#93707)

Lucas Faria0dfe0beb3552
diff --git a/frontend/src/scenes/surveys/CopySurveyLink.test.tsx b/frontend/src/scenes/surveys/CopySurveyLink.test.tsx
new file mode 100644
index 000000000000..c05fb07727f0
--- /dev/null
+++ b/frontend/src/scenes/surveys/CopySurveyLink.test.tsx
@@ -0,0 +1,11 @@
+import { getEmbedSnippet } from './CopySurveyLink'
+
+describe('getEmbedSnippet', () => {
+ it('accepts height messages from the sandboxed survey iframe', () => {
+ const snippet = getEmbedSnippet('survey-id')
+
+ expect(snippet).toContain('if (e.source !== iframe.contentWindow) return;')
+ expect(snippet).toContain("if (e.origin !== 'null' && e.origin !== 'http://localhost') return;")
+ expect(snippet).toContain("e.data.type === 'posthog:survey:height' && e.data.surveyId === 'survey-id'")
+ })
+})
diff --git a/frontend/src/scenes/surveys/CopySurveyLink.tsx b/frontend/src/scenes/surveys/CopySurveyLink.tsx
index a280eb87bf5c..5d13b120311f 100644
--- a/frontend/src/scenes/surveys/CopySurveyLink.tsx
+++ b/frontend/src/scenes/surveys/CopySurveyLink.tsx
@@ -10,7 +10,7 @@ export function getSurveyUrl(surveyId: string): string {
return url.toString()
}
-function getEmbedSnippet(surveyId: string): string {
+export function getEmbedSnippet(surveyId: string): string {
const surveyUrl = getSurveyUrl(surveyId)
return `<div id="posthog-survey-container-${surveyId}"></div>
<script>
@@ -41,7 +41,9 @@ function getEmbedSnippet(surveyId: string): string {
}
window.addEventListener('message', function(e) {
- if (e.origin !== '${new URL(surveyUrl).origin}') return;
+ // Sandboxed surveys have an opaque origin, so bind messages to this iframe's window.
+ if (e.source !== iframe.contentWindow) return;
+ if (e.origin !== 'null' && e.origin !== '${new URL(surveyUrl).origin}') return;
if (e.data.type === 'posthog:survey:height' && e.data.surveyId === '${surveyId}') {
var height = parseInt(e.data.height, 10);
if (height > 0 && height < 10000) {
diff --git a/posthog/templates/surveys/public_survey.html b/posthog/templates/surveys/public_survey.html
index e039086e266a..322584b1640e 100644
--- a/posthog/templates/surveys/public_survey.html
+++ b/posthog/templates/surveys/public_survey.html
@@ -436,7 +436,7 @@
capture_exceptions: false,
advanced_disable_flags: true,
advanced_enable_surveys: true,
- persistence: 'sessionStorage'
+ persistence: 'memory'
};
const distinctID = searchParams.get('distinct_id');
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index 5b2fa0157f25..e43573bbd863 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -113,6 +113,29 @@ DEFAULT_BASE_LANGUAGE = "en"
# Sentinel keys we explicitly reject — these used to appear in customer data and never
# resolved to anything in the SDK. Block them at the API so they don't keep accumulating.
REJECTED_TRANSLATION_KEYS = frozenset({"default", "original", "base"})
+SURVEY_APPEARANCE_HTML_FIELDS = (
+ "thankYouMessageHeader",
+ "thankYouMessageDescription",
+ "thankYouMessageCloseButtonText",
+ "introScreenHeader",
+ "introScreenDescription",
+ "introScreenButtonText",
+)
+SURVEY_QUESTION_HTML_FIELDS = (
+ "question",
+ "description",
+ "buttonText",
+ "lowerBoundLabel",
+ "upperBoundLabel",
+)
+SURVEY_TRANSLATION_HTML_FIELDS = (
+ "name",
+ "description",
+ "thankYouMessageHeader",
+ "thankYouMessageDescription",
+ "thankYouMessageCloseButtonText",
+ *SURVEY_QUESTION_HTML_FIELDS,
+)
def _normalize_language_code(raw: str) -> str:
@@ -120,6 +143,78 @@ def _normalize_language_code(raw: str) -> str:
return raw.strip().lower().replace("_", "-")
+def sanitize_survey_appearance(appearance: dict[str, Any]) -> dict[str, Any]:
+ sanitized_appearance = dict(appearance)
+ for field in SURVEY_APPEARANCE_HTML_FIELDS:
+ field_value = sanitized_appearance.get(field)
+ if isinstance(field_value, str) and nh3.is_html(field_value):
+ sanitized_appearance[field] = nh3_clean_with_allow_list(field_value)
+ return sanitized_appearance
+
+
+def _sanitize_survey_html(value: str) -> str:
+ return nh3_clean_with_allow_list(value) if nh3.is_html(value) else value
+
+
+def _sanitize_survey_link(link: str) -> str | None:
+ parsed_url = urlparse(link)
+ if parsed_url.scheme == "https" and parsed_url.netloc:
+ return _sanitize_survey_html(link)
+ if parsed_url.scheme == "mailto" and re.match(EMAIL_REGEX, link):
+ return _sanitize_survey_html(link)
+ return None
+
+
+def sanitize_survey_translations(translations: dict[str, Any]) -> dict[str, Any]:
+ sanitized_translations = dict(translations)
+ for language, translation in translations.items():
+ if not isinstance(translation, dict):
+ continue
+ sanitized_translation = dict(translation)
+ for field in SURVEY_TRANSLATION_HTML_FIELDS:
+ value = sanitized_translation.get(field)
+ if isinstance(value, str):
+ sanitized_translation[field] = _sanitize_survey_html(value)
+ choices = sanitized_translation.get("choices")
+ if isinstance(choices, list):
+ sanitized_translation["choices"] = [
+ _sanitize_survey_html(choice) if isinstance(choice, str) else choice for choice in choices
+ ]
+ if "link" in sanitized_translation:
+ link = sanitized_translation["link"]
+ sanitized_link = _sanitize_survey_link(link) if isinstance(link, str) else None
+ if sanitized_link is None:
+ sanitized_translation.pop("link")
+ else:
+ sanitized_translation["link"] = sanitized_link
+ sanitized_translations[language] = sanitized_translation
+ return sanitized_translations
+
+
+def sanitize_survey_question(question: dict[str, Any]) -> dict[str, Any]:
+ sanitized_question = dict(question)
+ for field in SURVEY_QUESTION_HTML_FIELDS:
+ value = sanitized_question.get(field)
+ if isinstance(value, str):
+ sanitized_question[field] = _sanitize_survey_html(value)
+ choices = sanitized_question.get("choices")
+ if isinstance(choices, list):
+ sanitized_question["choices"] = [
+ _sanitize_survey_html(choice) if isinstance(choice, str) else choice for choice in choices
+ ]
+ if "link" in sanitized_question:
+ link = sanitized_question["link"]
+ sanitized_link = _sanitize_survey_link(link) if isinstance(link, str) else None
+ if sanitized_link is None:
+ sanitized_question.pop("link")
+ else:
+ sanitized_question["link"] = sanitized_link
+ translations = sanitized_question.get("translations")
+ if isinstance(translations, dict):
+ sanitized_question["translations"] = sanitize_survey_translations(translations)
+ return sanitized_question
+
+
# Keep this in sync with SurveyAPISerializer's public runtime contract.
# Root survey description is intentionally excluded because customers have used it for internal notes.
SURVEY_API_TRANSLATION_FIELDS = frozenset(
@@ -868,6 +963,28 @@ class SurveySerializer(SearchMatchTypeSerializerMixin, UserAccessControlSerializ
def get_conditions(self, survey: Survey):
return get_survey_conditions_with_actions(survey)
+ def validate_appearance(self, value: dict[str, Any] | None) -> dict[str, Any] | None:
+ if value is None:
+ return value
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("Appearance must be an object")
+ return sanitize_survey_appearance(value)
+
+ def to_representation(self, instance: Survey) -> dict[str, Any]:
+ data = super().to_representation(instance)
+ appearance = data.get("appearance")
+ if isinstance(appearance, dict):
+ data["appearance"] = sanitize_survey_appearance(appearance)
+ questions = data.get("questions")
+ if isinstance(questions, list):
+ data["questions"] = [
+ sanitize_survey_question(question) if isinstance(question, dict) else question for question in questions
+ ]
+ translations = data.get("translations")
+ if isinstance(translations, dict):
+ data["translations"] = sanitize_survey_translations(translations)
+ return data
+
class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
linked_flag = MinimalFeatureFlagSerializer(read_only=True)
@@ -995,17 +1112,7 @@ class SurveySerializerCreateUpdateOnly(serializers.ModelSerializer):
if not isinstance(value, dict):
raise serializers.ValidationError("Appearance must be an object")
- thank_you_message = value.get("thankYouMessageHeader")
- if thank_you_message and nh3.is_html(thank_you_message):
- value["thankYouMessageHeader"] = nh3_clean_with_allow_list(thank_you_message)
-
- thank_you_description = value.get("thankYouMessageDescription")
- if thank_you_description and nh3.is_html(thank_you_description):
- value["thankYouMessageDescription"] = nh3_clean_with_allow_list(thank_you_description)
-
- thank_you_close_button = value.get("thankYouMessageCloseButtonText")
- if thank_you_close_button and nh3.is_html(thank_you_close_button):
- value["thankYouMessageCloseButtonText"] = nh3_clean_with_allow_list(thank_you_close_button)
+ value = sanitize_survey_appearance(value)
thank_you_description_content_type = value.get("thankYouMessageDescriptionContentType")
if thank_you_description_content_type and thank_you_description_content_type not in ["text", "html"]:
@@ -2122,6 +2229,7 @@ class SurveyFilterSet(FilterSet):
@extend_schema_view(
create=extend_schema(request=SurveySerializerCreateUpdateOnlySchema),
+ update=extend_schema(request=SurveySerializerCreateUpdateOnlySchema),
partial_update=extend_schema(request=SurveySerializerCreateUpdateOnlySchema),
list=extend_schema(
parameters=[
@@ -2142,10 +2250,9 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.
filterset_class = SurveyFilterSet
def get_serializer_class(self) -> type[serializers.Serializer]:
- if self.request.method == "POST" or self.request.method == "PATCH":
+ if self.request.method in ("POST", "PUT", "PATCH"):
return SurveySerializerCreateUpdateOnly
- else:
- return SurveySerializer
+ return SurveySerializer
def safely_get_queryset(self, queryset):
queryset = queryset.exclude(product_tour__isnull=False)
@@ -3375,7 +3482,7 @@ def get_survey_api_translations(
continue
safe_translation = {
- field: value
+ field: _sanitize_survey_html(value)
for field, value in translation.items()
if field in SURVEY_API_TRANSLATION_FIELDS and isinstance(value, str)
}
@@ -3460,11 +3567,14 @@ class SurveyAPISerializer(serializers.ModelSerializer):
next_question["translations"] = filtered
else:
next_question.pop("translations", None)
- cleaned.append(next_question)
+ cleaned.append(sanitize_survey_question(next_question))
return cleaned
def to_representation(self, instance: Survey) -> dict[str, Any]:
data = super().to_representation(instance)
+ appearance = data.get("appearance")
+ if isinstance(appearance, dict):
+ data["appearance"] = sanitize_survey_appearance(appearance)
if data.get("translations") is None:
data.pop("translations", None)
return data
@@ -3526,6 +3636,34 @@ def _survey_page_site_url() -> str:
return settings.SITE_URL
+def _public_survey_csp(request: HttpRequest) -> str:
+ nonce = getattr(request, "csp_nonce", "")
+ script_sources = ["'self'", f"'nonce-{nonce}'", "'strict-dynamic'"]
+ if settings.DEBUG or settings.TEST:
+ script_sources.append("http://localhost:8234")
+ elif settings.SITE_URL.endswith(".dev.posthog.dev"):
+ script_sources.append("https://*.dev.posthog.dev")
+ else:
+ script_sources.extend(["https://*.posthog.com", "https://*.i.posthog.com"])
+
+ return "; ".join(
+ [
+ "sandbox allow-scripts allow-forms allow-popups",
+ f"script-src {' '.join(script_sources)}",
+ "script-src-attr 'none'",
+ "object-src 'none'",
+ "base-uri 'none'",
+ ]
+ )
+
+
+def _isolate_public_survey_response(request: HttpRequest, response: HttpResponse) -> HttpResponse:
+ # This must omit allow-same-origin because hosted survey content shares a host with authenticated app sessions.
+ response["Content-Security-Policy"] = _public_survey_csp(request)
+ response["Referrer-Policy"] = "no-referrer"
+ return response
+
+
def _survey_error_response(
request: HttpRequest,
*,
@@ -3541,17 +3679,17 @@ def _survey_error_response(
}
if appearance is not None:
context["appearance"] = appearance
- return render(request, "surveys/error.html", context, status=status)
+ return _isolate_public_survey_response(request, render(request, "surveys/error.html", context, status=status))
@csrf_exempt
@axes_dispatch
-def public_survey_page(request, survey_id: str):
+def public_survey_page(request: HttpRequest, survey_id: str) -> HttpResponse:
"""
Server-side rendered public survey page with security and performance optimizations
"""
if request.method == "OPTIONS":
- return cors_response(request, HttpResponse(""))
+ return _isolate_public_survey_response(request, cors_response(request, HttpResponse("")))
# Input validation
if not UUIDT.is_valid_uuid(survey_id):
@@ -3643,7 +3781,7 @@ def public_survey_page(request, survey_id: str):
response["Cache-Control"] = f"public, max-age={CACHE_TIMEOUT_SECONDS}"
response["Vary"] = "Accept-Encoding" # Enable compression caching
- return response
+ return _isolate_public_survey_response(request, response)
@contextmanager
diff --git a/products/surveys/backend/api/test/test_external_surveys.py b/products/surveys/backend/api/test/test_external_surveys.py
index 495991a57fe1..a859b930f84d 100644
--- a/products/surveys/backend/api/test/test_external_surveys.py
+++ b/products/surveys/backend/api/test/test_external_surveys.py
@@ -175,11 +175,47 @@ class TestExternalSurveys(APIBaseTest):
response = self.client.get(f"/external_surveys/{survey.id}/")
assert response.status_code == 200
+ csp = response["Content-Security-Policy"]
+ csp_directives = csp.split("; ")
+ sandbox_tokens = csp_directives[0].split()
+ assert sandbox_tokens[0] == "sandbox"
+ assert "allow-scripts" in sandbox_tokens
+ assert "allow-same-origin" not in sandbox_tokens
+ assert "allow-popups-to-escape-sandbox" not in sandbox_tokens
+ assert "allow-top-navigation" not in sandbox_tokens
+ assert "script-src-attr 'none'" in csp_directives
+ assert "unsafe-inline" not in csp
+ assert response["Referrer-Policy"] == "no-referrer"
+
# Check security headers - iframe embedding disabled by default
assert response["X-Frame-Options"] == "DENY"
assert "Cache-Control" in response
assert "Vary" in response
+ def test_uses_memory_persistence_in_opaque_origin_sandbox(self) -> None:
+ survey = self.create_external_survey()
+
+ response = self.client.get(f"/external_surveys/{survey.id}/")
+
+ assert response.status_code == 200
+ content = response.content.decode()
+ assert "persistence: 'memory'" in content
+ assert "persistence: 'sessionStorage'" not in content
+
+ @parameterized.expand(
+ [
+ ("invalid_id", "not-a-uuid", 400),
+ ("missing_survey", str(uuid.uuid4()), 404),
+ ]
+ )
+ def test_error_responses_are_sandboxed(self, _name: str, survey_id: str, expected_status: int) -> None:
+ response = self.client.get(f"/external_surveys/{survey_id}/")
+
+ assert response.status_code == expected_status
+ sandbox_tokens = response["Content-Security-Policy"].split("; ", 1)[0].split()
+ assert sandbox_tokens[0] == "sandbox"
+ assert "allow-same-origin" not in sandbox_tokens
+
def test_iframe_embedding_enabled_removes_x_frame_options(self):
"""Test that X-Frame-Options is removed when iframe embedding is enabled"""
survey = self.create_external_survey(enable_iframe_embedding=True)
diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.py
index 072275a07c21..9ddf56fd78cf 100644
--- a/products/surveys/backend/api/test/test_survey.py
+++ b/products/surveys/backend/api/test/test_survey.py
@@ -534,6 +534,69 @@ class TestSurvey(APIBaseTest):
]
]
+ def test_sdk_payload_sanitizes_stored_survey_html(self) -> None:
+ survey = Survey.objects.create(
+ team=self.team,
+ name="Survey with formatted intro",
+ type="popover",
+ start_date=datetime(2026, 1, 1, tzinfo=UTC),
+ questions=[
+ {
+ "type": "link",
+ "id": "q1",
+ "question": '<strong>How are you?</strong><img src="invalid" onerror="void 0">',
+ "description": '<strong>Details</strong><img src="invalid" onerror="void 0">',
+ "descriptionContentType": "html",
+ "link": "javascript:alert(1)",
+ "translations": {
+ "es": {"description": '<strong>Detalles</strong><img src="invalid" onerror="void 0">'}
+ },
+ }
+ ],
+ appearance={"introScreenDescription": '<strong>Welcome</strong><img src="invalid" onerror="void 0">'},
+ translations={
+ "es": {"thankYouMessageDescription": '<strong>Gracias</strong><img src="invalid" onerror="void 0">'}
+ },
+ )
+
+ payload = get_surveys_response(self.team)
+ serialized_survey = next(item for item in payload["surveys"] if str(item["id"]) == str(survey.id))
+
+ assert "<strong>Welcome</strong>" in serialized_survey["appearance"]["introScreenDescription"]
+ assert "<strong>Details</strong>" in serialized_survey["questions"][0]["description"]
+ assert "link" not in serialized_survey["questions"][0]
+ assert "<strong>Detalles</strong>" in serialized_survey["questions"][0]["translations"]["es"]["description"]
+ assert "<strong>Gracias</strong>" in serialized_survey["translations"]["es"]["thankYouMessageDescription"]
+ assert "onerror" not in json.dumps(serialized_survey)
+
+ def test_detail_payload_sanitizes_stored_survey_html(self) -> None:
+ survey = Survey.objects.create(
+ team=self.team,
+ name="Survey with stored appearance text",
+ type="popover",
+ questions=[
+ {
+ "type": "open",
+ "id": "q1",
+ "question": "How are you?",
+ "description": '<strong>Details</strong><img src="invalid" onerror="void 0">',
+ "descriptionContentType": "html",
+ }
+ ],
+ appearance={"introScreenDescription": '<strong>Welcome</strong><img src="invalid" onerror="void 0">'},
+ translations={
+ "es": {"thankYouMessageDescription": '<strong>Gracias</strong><img src="invalid" onerror="void 0">'}
+ },
+ )
+
+ response = self.client.get(f"/api/projects/{self.team.id}/surveys/{survey.id}/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert "<strong>Welcome</strong>" in response.json()["appearance"]["introScreenDescription"]
+ assert "<strong>Details</strong>" in response.json()["questions"][0]["description"]
+ assert "<strong>Gracias</strong>" in response.json()["translations"]["es"]["thankYouMessageDescription"]
+ assert "onerror" not in json.dumps(response.json())
+
def test_sdk_payload_strips_non_runtime_question_fields(self) -> None:
self.team.survey_config = {"appearance": {"backgroundColor": "black"}}
self.team.save(update_fields=["survey_config"])
@@ -4268,6 +4331,69 @@ class TestSurveyQuestionValidation(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED, response_data
assert response_data["questions"][0]["branching"]["type"] == "end"
+ def test_create_survey_sanitizes_html_in_appearance_text(self) -> None:
+ appearance_fields = [
+ "thankYouMessageHeader",
+ "thankYouMessageDescription",
+ "thankYouMessageCloseButtonText",
+ "introScreenHeader",
+ "introScreenDescription",
+ "introScreenButtonText",
+ ]
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/surveys/",
+ data={
+ "name": "Survey with formatted appearance text",
+ "type": "popover",
+ "appearance": {
+ field: f'<strong>{field}</strong><img src="invalid" onerror="void 0">'
+ for field in appearance_fields
+ },
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ for field in appearance_fields:
+ sanitized_value = response.json()["appearance"][field]
+ assert f"<strong>{field}</strong>" in sanitized_value
+ assert "onerror" not in sanitized_value
+
+ def test_update_survey_sanitizes_html_in_appearance_text(self) -> None:
+ survey = Survey.objects.create(
+ team=self.team,
+ created_by=self.user,
+ name="Survey with an updated intro",
+ type="popover",
+ questions=[],
+ )
+
+ response = self.client.put(
+ f"/api/projects/{self.team.id}/surveys/{survey.id}/",
+ data={
+ "name": survey.name,
+ "type": survey.type,
+ "appearance": {
+ "introScreenDescription": '<strong>Welcome</strong><img src="invalid" onerror="void 0">'
+ },
+ "questions": [
+ {
+ "type": "open",
+ "question": "How are you?",
+ "description": '<strong>Details</strong><img src="invalid" onerror="void 0">',
+ "descriptionContentType": "html",
+ }
+ ],
+ },
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert "<strong>Welcome</strong>" in response.json()["appearance"]["introScreenDescription"]
+ assert "onerror" not in response.json()["appearance"]["introScreenDescription"]
+ assert "<strong>Details</strong>" in response.json()["questions"][0]["description"]
+ assert "onerror" not in response.json()["questions"][0]["description"]
+
class TestSurveyQuestionValidationWithEnterpriseFeatures(APIBaseTest):
def setUp(self):
diff --git a/products/surveys/frontend/generated/api.ts b/products/surveys/frontend/generated/api.ts
index d731c4ccd20c..d747088a2276 100644
--- a/products/surveys/frontend/generated/api.ts
+++ b/products/surveys/frontend/generated/api.ts
@@ -107,14 +107,14 @@ export const getSurveysUpdateUrl = (projectId: string, id: string) => {
export const surveysUpdate = async (
projectId: string,
id: string,
- surveyApi: NonReadonly<SurveyApi>,
+ surveySerializerCreateUpdateOnlySchemaApi: NonReadonly<SurveySerializerCreateUpdateOnlySchemaApi>,
options?: RequestInit
-): Promise<SurveyApi> => {
- return apiMutator<SurveyApi>(getSurveysUpdateUrl(projectId, id), {
+): Promise<SurveySerializerCreateUpdateOnlyApi> => {
+ return apiMutator<SurveySerializerCreateUpdateOnlyApi>(getSurveysUpdateUrl(projectId, id), {
...options,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(surveyApi),
+ body: JSON.stringify(surveySerializerCreateUpdateOnlySchemaApi),
})
}
diff --git a/products/surveys/frontend/generated/api.zod.ts b/products/surveys/frontend/generated/api.zod.ts
index 6005659ea4a4..4bd411797645 100644
--- a/products/surveys/frontend/generated/api.zod.ts
+++ b/products/surveys/frontend/generated/api.zod.ts
@@ -870,14 +870,26 @@ export const SurveysCreateBody = /* @__PURE__ */ zod.object({
export const surveysUpdateBodyNameMax = 400
-export const surveysUpdateBodyResponsesLimitMin = 0
-export const surveysUpdateBodyResponsesLimitMax = 2147483647
+export const surveysUpdateBodyTargetingFlagFiltersOneEarlyExitDefault = false
+export const surveysUpdateBodyQuestionsItemThreeBranchingOneThreeIndexMin = 0
+
+export const surveysUpdateBodyQuestionsItemThreeBranchingOneFourResponseValuesOneMin = 0
+
+export const surveysUpdateBodyQuestionsItemFourChoicesMin = 2
+export const surveysUpdateBodyQuestionsItemFourChoicesMax = 20
+
+export const surveysUpdateBodyQuestionsItemFourBranchingOneThreeIndexMin = 0
+
+export const surveysUpdateBodyQuestionsItemFourBranchingOneFourResponseValuesOneMin = 0
+
+export const surveysUpdateBodyQuestionsItemFiveChoicesMin = 2
+export const surveysUpdateBodyQuestionsItemFiveChoicesMax = 20
+
+export const surveysUpdateBodyConditionsOneSeenSurveyWaitPeriodInDaysMin = 0
-export const surveysUpdateBodyIterationCountMin = 0
export const surveysUpdateBodyIterationCountMax = 500
-export const surveysUpdateBodyIterationFrequencyDaysMin = 0
-export const surveysUpdateBodyIterationFrequencyDaysMax = 2147483647
+export const surveysUpdateBodyIterationFrequencyDaysMax = 365
export const surveysUpdateBodyCurrentIterationMin = 0
export const surveysUpdateBodyCurrentIterationMax = 2147483647
@@ -890,82 +902,830 @@ export const surveysUpdateBodyResponseSamplingLimitMax = 2147483647
export const surveysUpdateBodyBaseLanguageMax = 20
-export const SurveysUpdateBody = /* @__PURE__ */ zod
- .object({
- name: zod.string().max(surveysUpdateBodyNameMax),
- description: zod.string().optional(),
- type: zod
- .enum(['popover', 'widget', 'external_survey', 'api'])
- .describe(
- '\* `popover` - popover\n\* `widget` - widget\n\* `external_survey` - external survey\n\* `api` - api'
- ),
- schedule: zod.string().nullish(),
- linked_flag_id: zod.number().nullish(),
- linked_insight_id: zod.number().nullish(),
- questions: zod
- .unknown()
- .optional()
- .describe(
- '\n The `array` of questions included in the survey. Each question must conform to one of the defined question types: Basic, Link, Rating, or Multiple Choice.\n\n Basic (open-ended question)\n - `id`: The question ID\n - `type`: `open`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Link (a question with a link)\n - `id`: The question ID\n - `type`: `link`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `link`: The URL associated with the question.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Rating (a question with a rating scale)\n - `id`: The question ID\n - `type`: `rating`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `display`: Display style of the rating (`number` or `emoji`).\n - `scale`: The scale of the rating (`number`).\n - `lowerBoundLabel`: Label for the lower bound of the scale.\n - `upperBoundLabel`: Label for the upper bound of the scale.\n - `isNpsQuestion`: Whether the question is an NPS rating.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Multiple choice\n - `id`: The question ID\n - `type`: `single_choice` or `multiple_choice`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `choices`: An array of choices for the question.\n - `shuffleOptions`: Whether to shuffle the order of the choices (`boolean`).\n - `hasOpenChoice`: Whether the question allows an open-ended response (`boolean`).\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Branching logic can be one of the following types:\n\n Next question: Proceeds to the next question\n ```json\n {\n \"type\": \"next_question\"\n }\n ```\n\n End: Ends the survey, optionally displaying a confirmation message.\n ```json\n {\n \"type\": \"end\"\n }\n ```\n\n Response-based: Branches based on the response values. Available for the `rating` and `single_choice` question types.\n ```json\n {\n \"type\": \"response_based\",\n \"responseValues\": {\n \"responseKey\": \"value\"\n }\n }\n ```\n\n Specific question: Proceeds to a specific question by index.\n ```json\n {\n \"type\": \"specific_question\",\n \"index\": 2\n }\n ```\n\n Translations: Each question can include inline translations.\n - `translations`: Object mapping language codes to translated fields.\n - Language codes: Canonical BCP-47-ish strings (e.g., \"es\", \"es-MX\", \"zh-CN\"). Aliases like \"english\" or \"default\" are rejected. The survey\'s `base_language` (default \"en\") declares the language of the untranslated text and cannot also appear as a translation key.\n - Translatable fields: `question`, `description`, `buttonText`, `choices`, `lowerBoundLabel`, `upperBoundLabel`, `link`\n\n Example with translations:\n ```json\n {\n \"id\": \"uuid\",\n \"type\": \"rating\",\n \"question\": \"How satisfied are you?\",\n \"lowerBoundLabel\": \"Not satisfied\",\n \"upperBoundLabel\": \"Very satisfied\",\n \"translations\": {\n \"es\": {\n \"question\": \"¿Qué tan satisfecho estás?\",\n \"lowerBoundLabel\": \"No satisfecho\",\n \"upperBoundLabel\": \"Muy satisfecho\"\n },\n \"fr\": {\n \"question\": \"Dans quelle mesure êtes-vous satisfait?\"\n }\n }\n }\n ```\n '
- ),
- appearance: zod.unknown().optional(),
- start_date: zod.iso.datetime({ offset: true }).nullish(),
- end_date: zod.iso.datetime({ offset: true }).nullish(),
- archived: zod.boolean().optional(),
- responses_limit: zod
- .number()
- .min(surveysUpdateBodyResponsesLimitMin)
- .max(surveysUpdateBodyResponsesLimitMax)
- .nullish(),
- iteration_count: zod
- .number()
- .min(surveysUpdateBodyIterationCountMin)
- .max(surveysUpdateBodyIterationCountMax)
- .nullish(),
- iteration_frequency_days: zod
- .number()
- .min(surveysUpdateBodyIterationFrequencyDaysMin)
- .max(surveysUpdateBodyIterationFrequencyDaysMax)
- .nullish(),
- iteration_start_dates: zod.array(zod.iso.datetime({ offset: true }).nullable()).nullish(),
- current_iteration: zod
- .number()
- .min(surveysUpdateBodyCurrentIterationMin)
- .max(surveysUpdateBodyCurrentIterationMax)
- .nullish(),
- current_iteration_start_date: zod.iso.datetime({ offset: true }).nullish(),
- response_sampling_start_date: zod.iso.datetime({ offset: true }).nullish(),
- response_sampling_interval_type: zod
- .union([
- zod.enum(['day', 'week', 'month']).describe('\* `day` - day\n\* `week` - week\n\* `month` - month'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional(),
- response_sampling_interval: zod
- .number()
- .min(surveysUpdateBodyResponseSamplingIntervalMin)
- .max(surveysUpdateBodyResponseSamplingIntervalMax)
- .nullish(),
- response_sampling_limit: zod
- .number()
- .min(surveysUpdateBodyResponseSamplingLimitMin)
- .max(surveysUpdateBodyResponseSamplingLimitMax)
- .nullish(),
- response_sampling_daily_limits: zod.unknown().optional(),
- enable_partial_responses: zod.boolean().nullish(),
- enable_iframe_embedding: zod.boolean().nullish(),
- base_language: zod
- .string()
- .max(surveysUpdateBodyBaseLanguageMax)
- .optional()
- .describe(
- "BCP-47 language code (e.g. 'en', 'es', 'es-MX') describing the language of the survey's untranslated text. Defaults to 'en'. Cannot also appear as a key in `translations`."
- ),
- translations: zod.unknown().optional(),
- form_content: zod.unknown().optional(),
- })
- .describe('Mixin for serializers to add user access control fields')
+export const SurveysUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .min(1)
+ .max(surveysUpdateBodyNameMax)
+ .describe(
+ "Survey name. Anyone can read it. In-app surveys send it to every visitor's browser alongside the questions and appearance text, and a hosted survey shows it on its public page. Keep customer names and other private details out of it."
+ ),
+ description: zod
+ .string()
+ .optional()
+ .describe(
+ 'Survey description. Internal only: unlike the name and questions, it is never delivered to visitors.'
+ ),
+ type: zod
+ .enum(['popover', 'widget', 'external_survey', 'api'])
+ .describe(
+ '\* `popover` - popover\n\* `widget` - widget\n\* `external_survey` - external survey\n\* `api` - api'
+ )
+ .describe(
+ 'Survey type.\n\n\* `popover` - popover\n\* `widget` - widget\n\* `external_survey` - external survey\n\* `api` - api'
+ ),
+ schedule: zod
+ .union([
+ zod
+ .enum(['once', 'recurring', 'always'])
+ .describe('\* `once` - once\n\* `recurring` - recurring\n\* `always` - always'),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Survey scheduling behavior: 'once' = show once per user (default), 'recurring' = repeat based on iteration_count and iteration_frequency_days settings, 'always' = show every time conditions are met (mainly for widget surveys)\n\n\* `once` - once\n\* `recurring` - recurring\n\* `always` - always"
+ ),
+ linked_flag_id: zod.number().nullish().describe('The feature flag linked to this survey.'),
+ linked_insight_id: zod.number().nullish(),
+ targeting_flag_id: zod.number().optional().describe('An existing targeting flag to use for this survey.'),
+ targeting_flag_filters: zod
+ .union([
+ zod.object({
+ groups: zod
+ .array(
+ zod.object({
+ properties: zod
+ .array(
+ zod.union([
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['cohort', 'person', 'group'])
+ .describe(
+ '\* `cohort` - cohort\n\* `person` - person\n\* `group` - group'
+ )
+ .optional()
+ .describe(
+ "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n\* `cohort` - cohort\n\* `person` - person\n\* `group` - group"
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ value: zod
+ .unknown()
+ .describe(
+ 'Comparison value for the property filter. Supports strings, numbers, booleans, and arrays.'
+ ),
+ operator: zod
+ .enum([
+ 'exact',
+ 'is_not',
+ 'icontains',
+ 'not_icontains',
+ 'starts_with',
+ 'not_starts_with',
+ 'ends_with',
+ 'not_ends_with',
+ 'regex',
+ 'not_regex',
+ 'gt',
+ 'gte',
+ 'lt',
+ 'lte',
+ ])
+ .describe(
+ '\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `gte` - gte\n\* `lt` - lt\n\* `lte` - lte'
+ )
+ .describe(
+ 'Operator used to compare the property value.\n\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains\n\* `starts_with` - starts_with\n\* `not_starts_with` - not_starts_with\n\* `ends_with` - ends_with\n\* `not_ends_with` - not_ends_with\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `gt` - gt\n\* `gte` - gte\n\* `lt` - lt\n\* `lte` - lte'
+ ),
+ }),
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['cohort', 'person', 'group'])
+ .describe(
+ '\* `cohort` - cohort\n\* `person` - person\n\* `group` - group'
+ )
+ .optional()
+ .describe(
+ "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n\* `cohort` - cohort\n\* `person` - person\n\* `group` - group"
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ operator: zod
+ .enum(['is_set', 'is_not_set'])
+ .describe('\* `is_set` - is_set\n\* `is_not_set` - is_not_set')
+ .describe(
+ 'Existence operator.\n\n\* `is_set` - is_set\n\* `is_not_set` - is_not_set'
+ ),
+ value: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Optional value. Runtime behavior determines whether this is ignored.'
+ ),
+ }),
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['cohort', 'person', 'group'])
+ .describe(
+ '\* `cohort` - cohort\n\* `person` - person\n\* `group` - group'
+ )
+ .optional()
+ .describe(
+ "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n\* `cohort` - cohort\n\* `person` - person\n\* `group` - group"
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ operator: zod
+ .enum(['is_date_exact', 'is_date_before', 'is_date_after'])
+ .describe(
+ '\* `is_date_exact` - is_date_exact\n\* `is_date_before` - is_date_before\n\* `is_date_after` - is_date_after'
+ )
+ .describe(
+ 'Date comparison operator.\n\n\* `is_date_exact` - is_date_exact\n\* `is_date_after` - is_date_after\n\* `is_date_before` - is_date_before'
+ ),
+ value: zod
+ .string()
+ .describe('Date value in ISO format or relative date expression.'),
+ }),
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['cohort', 'person', 'group'])
+ .describe(
+ '\* `cohort` - cohort\n\* `person` - person\n\* `group` - group'
+ )
+ .optional()
+ .describe(
+ "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n\* `cohort` - cohort\n\* `person` - person\n\* `group` - group"
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ operator: zod
+ .enum([
+ 'semver_gt',
+ 'semver_gte',
+ 'semver_lt',
+ 'semver_lte',
+ 'semver_eq',
+ 'semver_neq',
+ 'semver_tilde',
+ 'semver_caret',
+ 'semver_wildcard',
+ ])
+ .describe(
+ '\* `semver_gt` - semver_gt\n\* `semver_gte` - semver_gte\n\* `semver_lt` - semver_lt\n\* `semver_lte` - semver_lte\n\* `semver_eq` - semver_eq\n\* `semver_neq` - semver_neq\n\* `semver_tilde` - semver_tilde\n\* `semver_caret` - semver_caret\n\* `semver_wildcard` - semver_wildcard'
+ )
+ .describe(
+ 'Semantic version comparison operator.\n\n\* `semver_gt` - semver_gt\n\* `semver_gte` - semver_gte\n\* `semver_lt` - semver_lt\n\* `semver_lte` - semver_lte\n\* `semver_eq` - semver_eq\n\* `semver_neq` - semver_neq\n\* `semver_tilde` - semver_tilde\n\* `semver_caret` - semver_caret\n\* `semver_wildcard` - semver_wildcard'
+ ),
+ value: zod.string().describe('Semantic version string.'),
+ }),
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['cohort', 'person', 'group'])
+ .describe(
+ '\* `cohort` - cohort\n\* `person` - person\n\* `group` - group'
+ )
+ .optional()
+ .describe(
+ "Property filter type. Set it on every property. Use `group` with `group_type_index` to filter on a group's properties.\n\n\* `cohort` - cohort\n\* `person` - person\n\* `group` - group"
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ operator: zod
+ .enum(['icontains_multi', 'not_icontains_multi'])
+ .describe(
+ '\* `icontains_multi` - icontains_multi\n\* `not_icontains_multi` - not_icontains_multi'
+ )
+ .describe(
+ 'Multi-contains operator.\n\n\* `icontains_multi` - icontains_multi\n\* `not_icontains_multi` - not_icontains_multi'
+ ),
+ value: zod
+ .array(zod.string())
+ .describe('List of strings to evaluate against.'),
+ }),
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['cohort'])
+ .describe('\* `cohort` - cohort')
+ .describe(
+ 'Cohort property type required for in\/not_in operators.\n\n\* `cohort` - cohort'
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ operator: zod
+ .enum(['in', 'not_in'])
+ .describe('\* `in` - in\n\* `not_in` - not_in')
+ .describe(
+ 'Membership operator for cohort properties.\n\n\* `in` - in\n\* `not_in` - not_in'
+ ),
+ value: zod
+ .unknown()
+ .describe(
+ 'Cohort comparison value (single or list, depending on usage).'
+ ),
+ }),
+ zod.object({
+ key: zod
+ .string()
+ .describe('Property key used in this feature flag condition.'),
+ type: zod
+ .enum(['flag'])
+ .describe('\* `flag` - flag')
+ .describe(
+ 'Flag property type required for flag dependency checks.\n\n\* `flag` - flag'
+ ),
+ cohort_name: zod
+ .string()
+ .nullish()
+ .describe('Resolved cohort name for cohort-type filters.'),
+ group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ "Group type index a `group` filter reads properties from. Defaults to the condition set's `aggregation_group_type_index`."
+ ),
+ operator: zod
+ .enum(['flag_evaluates_to'])
+ .describe('\* `flag_evaluates_to` - flag_evaluates_to')
+ .describe(
+ 'Operator for feature flag dependency evaluation.\n\n\* `flag_evaluates_to` - flag_evaluates_to'
+ ),
+ value: zod.unknown().describe('Value to compare flag evaluation against.'),
+ }),
+ ])
+ )
+ .optional()
+ .describe('Property conditions for this release condition group.'),
+ rollout_percentage: zod
+ .number()
+ .optional()
+ .describe('Rollout percentage for this release condition group.'),
+ variant: zod.string().nullish().describe('Variant key override for multivariate flags.'),
+ aggregation_group_type_index: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Group type index for this condition set. None means person-level aggregation.'
+ ),
+ })
+ )
+ .optional()
+ .describe('Release condition groups for the feature flag.'),
+ multivariate: zod
+ .union([
+ zod.object({
+ variants: zod
+ .array(
+ zod.object({
+ key: zod.string().describe('Unique key for this variant.'),
+ name: zod.string().optional().describe('Human-readable name for this variant.'),
+ rollout_percentage: zod.number().describe('Variant rollout percentage.'),
+ })
+ )
+ .describe('Variant definitions for multivariate feature flags.'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Multivariate configuration for variant-based rollouts.'),
+ aggregation_group_type_index: zod
+ .number()
+ .nullish()
+ .describe('Group type index for group-based feature flags.'),
+ payloads: zod
+ .record(zod.string(), zod.string())
+ .optional()
+ .describe('Optional payload values keyed by variant key.'),
+ feature_enrollment: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether this flag has early access feature enrollment enabled. When true, the flag is evaluated against the person property $feature_enrollment\/{flag_key}.'
+ ),
+ early_exit: zod
+ .boolean()
+ .default(surveysUpdateBodyTargetingFlagFiltersOneEarlyExitDefault)
+ .describe(
+ 'When true, condition evaluation stops at the first matching condition set rather than continuing to evaluate subsequent groups.'
+ ),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe(
+ "Target specific users based on their properties. Example: {groups: [{properties: [{key: 'email', value: ['@company.com'], operator: 'icontains'}], rollout_percentage: 100}]}"
+ ),
+ remove_targeting_flag: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Set to true to completely remove all targeting filters from the survey, making it visible to all users (subject to other display conditions like URL matching).'
+ ),
+ questions: zod
+ .array(
+ zod.union([
+ zod.object({
+ id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Stable question identifier (UUID). When editing an existing question, send back its current id so its responses (keyed by $survey_response_<id>) stay attached; omit it for new questions and the server generates one.'
+ ),
+ type: zod.enum(['open']).describe('\* `open` - open'),
+ question: zod.string().describe('Question text shown to respondents.'),
+ description: zod.string().optional().describe('Optional helper text.'),
+ descriptionContentType: zod
+ .enum(['html', 'text'])
+ .describe('\* `html` - html\n\* `text` - text')
+ .optional()
+ .describe('Format for the description field.\n\n\* `text` - text\n\* `html` - html'),
+ optional: zod.boolean().optional().describe('Whether respondents may skip this question.'),
+ buttonText: zod.string().optional().describe('Custom button label.'),
+ }),
+ zod.object({
+ id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Stable question identifier (UUID). When editing an existing question, send back its current id so its responses (keyed by $survey_response_<id>) stay attached; omit it for new questions and the server generates one.'
+ ),
+ type: zod.enum(['link']).describe('\* `link` - link'),
+ question: zod.string().describe('Question text shown to respondents.'),
+ description: zod.string().optional().describe('Optional helper text.'),
+ descriptionContentType: zod
+ .enum(['html', 'text'])
+ .describe('\* `html` - html\n\* `text` - text')
+ .optional()
+ .describe('Format for the description field.\n\n\* `text` - text\n\* `html` - html'),
+ optional: zod.boolean().optional().describe('Whether respondents may skip this question.'),
+ buttonText: zod.string().optional().describe('Custom button label.'),
+ link: zod.string().describe('HTTPS or mailto URL for link questions.'),
+ }),
+ zod.object({
+ id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Stable question identifier (UUID). When editing an existing question, send back its current id so its responses (keyed by $survey_response_<id>) stay attached; omit it for new questions and the server generates one.'
+ ),
+ type: zod.enum(['rating']).describe('\* `rating` - rating'),
+ question: zod.string().describe('Question text shown to respondents.'),
+ description: zod.string().optional().describe('Optional helper text.'),
+ descriptionContentType: zod
+ .enum(['html', 'text'])
+ .describe('\* `html` - html\n\* `text` - text')
+ .optional()
+ .describe('Format for the description field.\n\n\* `text` - text\n\* `html` - html'),
+ optional: zod.boolean().optional().describe('Whether respondents may skip this question.'),
+ buttonText: zod.string().optional().describe('Custom button label.'),
+ display: zod
+ .enum(['number', 'emoji'])
+ .describe('\* `number` - number\n\* `emoji` - emoji')
+ .optional()
+ .describe(
+ "Display format: 'number' shows numeric scale, 'emoji' shows emoji scale.\n\n\* `number` - number\n\* `emoji` - emoji"
+ ),
+ scale: zod.number().min(1).optional().describe('Rating scale can be one of 3, 5, or 7'),
+ lowerBoundLabel: zod
+ .string()
+ .optional()
+ .describe("Label for the lowest rating (e.g., 'Very Poor')"),
+ upperBoundLabel: zod
+ .string()
+ .optional()
+ .describe("Label for the highest rating (e.g., 'Excellent')"),
+ branching: zod
+ .union([
+ zod.union([
+ zod.object({
+ type: zod
+ .enum(['next_question'])
+ .describe('\* `next_question` - next_question')
+ .describe(
+ 'Continue to the next question in sequence.\n\n\* `next_question` - next_question'
+ ),
+ }),
+ zod.object({
+ type: zod
+ .enum(['end'])
+ .describe('\* `end` - end')
+ .describe('End the survey.\n\n\* `end` - end'),
+ }),
+ zod.object({
+ type: zod
+ .enum(['specific_question'])
+ .describe('\* `specific_question` - specific_question')
+ .describe(
+ 'Jump to a specific question index.\n\n\* `specific_question` - specific_question'
+ ),
+ index: zod
+ .number()
+ .min(surveysUpdateBodyQuestionsItemThreeBranchingOneThreeIndexMin)
+ .describe('0-based index of the next question.'),
+ }),
+ zod.object({
+ type: zod
+ .enum(['response_based'])
+ .describe('\* `response_based` - response_based')
+ .describe(
+ 'Branch based on the selected or entered response.\n\n\* `response_based` - response_based'
+ ),
+ responseValues: zod
+ .record(
+ zod.string(),
+ zod.union([
+ zod
+ .number()
+ .min(
+ surveysUpdateBodyQuestionsItemThreeBranchingOneFourResponseValuesOneMin
+ ),
+ zod.enum(['end']),
+ ])
+ )
+ .describe(
+ "Response-based branching map. Values can be a question index or 'end'."
+ ),
+ }),
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.object({
+ id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Stable question identifier (UUID). When editing an existing question, send back its current id so its responses (keyed by $survey_response_<id>) stay attached; omit it for new questions and the server generates one.'
+ ),
+ type: zod.enum(['single_choice']).describe('\* `single_choice` - single_choice'),
+ question: zod.string().describe('Question text shown to respondents.'),
+ description: zod.string().optional().describe('Optional helper text.'),
+ descriptionContentType: zod
+ .enum(['html', 'text'])
+ .describe('\* `html` - html\n\* `text` - text')
+ .optional()
+ .describe('Format for the description field.\n\n\* `text` - text\n\* `html` - html'),
+ optional: zod.boolean().optional().describe('Whether respondents may skip this question.'),
+ buttonText: zod.string().optional().describe('Custom button label.'),
+ choices: zod
+ .array(zod.string())
+ .min(surveysUpdateBodyQuestionsItemFourChoicesMin)
+ .max(surveysUpdateBodyQuestionsItemFourChoicesMax)
+ .describe(
+ 'Array of choice options. Choice indices (0, 1, 2, ...) are used for branching logic.'
+ ),
+ shuffleOptions: zod
+ .boolean()
+ .optional()
+ .describe('Whether to randomize the order of choices for each respondent.'),
+ hasOpenChoice: zod
+ .boolean()
+ .optional()
+ .describe("Whether the final option should be an open-text choice (for example, 'Other')."),
+ branching: zod
+ .union([
+ zod.union([
+ zod.object({
+ type: zod
+ .enum(['next_question'])
+ .describe('\* `next_question` - next_question')
+ .describe(
+ 'Continue to the next question in sequence.\n\n\* `next_question` - next_question'
+ ),
+ }),
+ zod.object({
+ type: zod
+ .enum(['end'])
+ .describe('\* `end` - end')
+ .describe('End the survey.\n\n\* `end` - end'),
+ }),
+ zod.object({
+ type: zod
+ .enum(['specific_question'])
+ .describe('\* `specific_question` - specific_question')
+ .describe(
+ 'Jump to a specific question index.\n\n\* `specific_question` - specific_question'
+ ),
+ index: zod
+ .number()
+ .min(surveysUpdateBodyQuestionsItemFourBranchingOneThreeIndexMin)
+ .describe('0-based index of the next question.'),
+ }),
+ zod.object({
+ type: zod
+ .enum(['response_based'])
+ .describe('\* `response_based` - response_based')
+ .describe(
+ 'Branch based on the selected or entered response.\n\n\* `response_based` - response_based'
+ ),
+ responseValues: zod
+ .record(
+ zod.string(),
+ zod.union([
+ zod
+ .number()
+ .min(
+ surveysUpdateBodyQuestionsItemFourBranchingOneFourResponseValuesOneMin
+ ),
+ zod.enum(['end']),
+ ])
+ )
+ .describe(
+ "Response-based branching map. Values can be a question index or 'end'."
+ ),
+ }),
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.object({
+ id: zod
+ .string()
+ .optional()
+ .describe(
+ 'Stable question identifier (UUID). When editing an existing question, send back its current id so its responses (keyed by $survey_response_<id>) stay attached; omit it for new questions and the server generates one.'
+ ),
+ type: zod.enum(['multiple_choice']).describe('\* `multiple_choice` - multiple_choice'),
+ question: zod.string().describe('Question text shown to respondents.'),
+ description: zod.string().optional().describe('Optional helper text.'),
+ descriptionContentType: zod
+ .enum(['html', 'text'])
+ .describe('\* `html` - html\n\* `text` - text')
+ .optional()
+ .describe('Format for the description field.\n\n\* `text` - text\n\* `html` - html'),
+ optional: zod.boolean().optional().describe('Whether respondents may skip this question.'),
+ buttonText: zod.string().optional().describe('Custom button label.'),
+ choices: zod
+ .array(zod.string())
+ .min(surveysUpdateBodyQuestionsItemFiveChoicesMin)
+ .max(surveysUpdateBodyQuestionsItemFiveChoicesMax)
+ .describe(
+ 'Array of choice options. Multiple selections allowed. No branching logic supported.'
+ ),
+ shuffleOptions: zod
+ .boolean()
+ .optional()
+ .describe('Whether to randomize the order of choices for each respondent.'),
+ hasOpenChoice: zod
+ .boolean()
+ .optional()
+ .describe("Whether the final option should be an open-text choice (for example, 'Other')."),
+ }),
+ ])
+ )
+ .nullish()
+ .describe(
+ '\n The `array` of questions included in the survey. Each question must conform to one of the defined question types: Basic, Link, Rating, or Multiple Choice.\n\n Basic (open-ended question)\n - `id`: The question ID\n - `type`: `open`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Link (a question with a link)\n - `id`: The question ID\n - `type`: `link`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `link`: The URL associated with the question.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Rating (a question with a rating scale)\n - `id`: The question ID\n - `type`: `rating`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `display`: Display style of the rating (`number` or `emoji`).\n - `scale`: The scale of the rating (`number`).\n - `lowerBoundLabel`: Label for the lower bound of the scale.\n - `upperBoundLabel`: Label for the upper bound of the scale.\n - `isNpsQuestion`: Whether the question is an NPS rating.\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Multiple choice\n - `id`: The question ID\n - `type`: `single_choice` or `multiple_choice`\n - `question`: The text of the question.\n - `description`: Optional description of the question.\n - `descriptionContentType`: Content type of the description (`html` or `text`).\n - `optional`: Whether the question is optional (`boolean`).\n - `buttonText`: Text displayed on the submit button.\n - `choices`: An array of choices for the question.\n - `shuffleOptions`: Whether to shuffle the order of the choices (`boolean`).\n - `hasOpenChoice`: Whether the question allows an open-ended response (`boolean`).\n - `branching`: Branching logic for the question. See branching types below for details.\n\n Branching logic can be one of the following types:\n\n Next question: Proceeds to the next question\n ```json\n {\n \"type\": \"next_question\"\n }\n ```\n\n End: Ends the survey, optionally displaying a confirmation message.\n ```json\n {\n \"type\": \"end\"\n }\n ```\n\n Response-based: Branches based on the response values. Available for the `rating` and `single_choice` question types.\n ```json\n {\n \"type\": \"response_based\",\n \"responseValues\": {\n \"responseKey\": \"value\"\n }\n }\n ```\n\n Specific question: Proceeds to a specific question by index.\n ```json\n {\n \"type\": \"specific_question\",\n \"index\": 2\n }\n ```\n\n Translations: Each question can include inline translations.\n - `translations`: Object mapping language codes to translated fields.\n - Language codes: Canonical BCP-47-ish strings (e.g., \"es\", \"es-MX\", \"zh-CN\"). Aliases like \"english\" or \"default\" are rejected. The survey\'s `base_language` (default \"en\") declares the language of the untranslated text and cannot also appear as a translation key.\n - Translatable fields: `question`, `description`, `buttonText`, `choices`, `lowerBoundLabel`, `upperBoundLabel`, `link`\n\n Example with translations:\n ```json\n {\n \"id\": \"uuid\",\n \"type\": \"rating\",\n \"question\": \"How satisfied are you?\",\n \"lowerBoundLabel\": \"Not satisfied\",\n \"upperBoundLabel\": \"Very satisfied\",\n \"translations\": {\n \"es\": {\n \"question\": \"¿Qué tan satisfecho estás?\",\n \"lowerBoundLabel\": \"No satisfecho\",\n \"upperBoundLabel\": \"Muy satisfecho\"\n },\n \"fr\": {\n \"question\": \"Dans quelle mesure êtes-vous satisfait?\"\n }\n }\n }\n ```\n '
+ ),
+ conditions: zod
+ .union([
+ zod.object({
+ url: zod.string().optional(),
+ selector: zod.string().optional(),
+ seenSurveyWaitPeriodInDays: zod
+ .number()
+ .min(surveysUpdateBodyConditionsOneSeenSurveyWaitPeriodInDaysMin)
+ .optional()
+ .describe("Don't show this survey to users who saw any survey in the last x days."),
+ urlMatchType: zod
+ .enum(['regex', 'not_regex', 'exact', 'is_not', 'icontains', 'not_icontains'])
+ .describe(
+ '\* `regex` - regex\n\* `not_regex` - not_regex\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains'
+ )
+ .optional()
+ .describe(
+ "URL\/device matching types: 'regex' (matches regex pattern), 'not_regex' (does not match regex pattern), 'exact' (exact string match), 'is_not' (not exact match), 'icontains' (case-insensitive contains), 'not_icontains' (case-insensitive does not contain).\n\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains"
+ ),
+ events: zod
+ .object({
+ repeatedActivation: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether to show the survey every time one of the events is triggered (true), or just once (false).'
+ ),
+ values: zod
+ .array(
+ zod.object({
+ name: zod.string().describe('Event name that triggers the survey.'),
+ })
+ )
+ .optional()
+ .describe('Array of event names that trigger the survey.'),
+ })
+ .optional(),
+ deviceTypes: zod
+ .array(
+ zod
+ .enum(['Desktop', 'Mobile', 'Tablet'])
+ .describe('\* `Desktop` - Desktop\n\* `Mobile` - Mobile\n\* `Tablet` - Tablet')
+ )
+ .optional()
+ .describe('Device types that should match for this survey to be shown.'),
+ deviceTypesMatchType: zod
+ .enum(['regex', 'not_regex', 'exact', 'is_not', 'icontains', 'not_icontains'])
+ .describe(
+ '\* `regex` - regex\n\* `not_regex` - not_regex\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains'
+ )
+ .optional()
+ .describe(
+ "URL\/device matching types: 'regex' (matches regex pattern), 'not_regex' (does not match regex pattern), 'exact' (exact string match), 'is_not' (not exact match), 'icontains' (case-insensitive contains), 'not_icontains' (case-insensitive does not contain).\n\n\* `regex` - regex\n\* `not_regex` - not_regex\n\* `exact` - exact\n\* `is_not` - is_not\n\* `icontains` - icontains\n\* `not_icontains` - not_icontains"
+ ),
+ linkedFlagVariant: zod
+ .string()
+ .optional()
+ .describe('The variant of the feature flag linked to this survey.'),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Display and targeting conditions for the survey.'),
+ appearance: zod
+ .union([
+ zod.object({
+ backgroundColor: zod.string().optional(),
+ submitButtonColor: zod.string().optional(),
+ textColor: zod.string().optional(),
+ submitButtonText: zod.string().optional(),
+ submitButtonTextColor: zod.string().optional(),
+ descriptionTextColor: zod.string().optional(),
+ ratingButtonColor: zod.string().optional(),
+ ratingButtonActiveColor: zod.string().optional(),
+ ratingButtonHoverColor: zod.string().optional(),
+ whiteLabel: zod.boolean().optional(),
+ autoDisappear: zod.boolean().optional(),
+ displayThankYouMessage: zod.boolean().optional(),
+ thankYouMessageHeader: zod.string().optional(),
+ thankYouMessageDescription: zod.string().optional(),
+ thankYouMessageDescriptionContentType: zod
+ .enum(['html', 'text'])
+ .optional()
+ .describe('\* `html` - html\n\* `text` - text'),
+ thankYouMessageCloseButtonText: zod.string().optional(),
+ borderColor: zod.string().optional(),
+ placeholder: zod.string().optional(),
+ shuffleQuestions: zod.boolean().optional(),
+ surveyPopupDelaySeconds: zod.number().optional(),
+ allowGoBack: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Whether to show a 'Back' button on web surveys after the first question, letting respondents return to a previously visited question. Defaults to false."
+ ),
+ backButtonText: zod
+ .string()
+ .optional()
+ .describe("Optional override for the back button label. Defaults to 'Back'."),
+ widgetType: zod
+ .enum(['button', 'tab', 'selector'])
+ .optional()
+ .describe('\* `button` - button\n\* `tab` - tab\n\* `selector` - selector'),
+ widgetSelector: zod.string().optional(),
+ widgetLabel: zod.string().optional(),
+ widgetColor: zod.string().optional(),
+ fontFamily: zod.string().optional(),
+ maxWidth: zod.string().optional(),
+ zIndex: zod.string().optional(),
+ disabledButtonOpacity: zod.string().optional(),
+ boxPadding: zod.string().optional(),
+ }),
+ zod.null(),
+ ])
+ .optional()
+ .describe('Survey appearance customization.'),
+ start_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ "Setting this will launch the survey immediately. Don't add a start_date unless explicitly requested to do so."
+ ),
+ end_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When the survey stopped being shown to users. Setting this will complete the survey.'),
+ archived: zod.boolean().optional().describe('Archive state for the survey.'),
+ responses_limit: zod
+ .number()
+ .nullish()
+ .describe('The maximum number of responses before automatically stopping the survey.'),
+ iteration_count: zod
+ .number()
+ .min(1)
+ .max(surveysUpdateBodyIterationCountMax)
+ .nullish()
+ .describe(
+ "For a recurring schedule, this field specifies the number of times the survey should be shown to the user. Use 1 for 'once every X days', higher numbers for multiple repetitions. Works together with iteration_frequency_days to determine the overall survey schedule."
+ ),
+ iteration_frequency_days: zod
+ .number()
+ .min(1)
+ .max(surveysUpdateBodyIterationFrequencyDaysMax)
+ .nullish()
+ .describe(
+ 'For a recurring schedule, this field specifies the interval in days between each survey instance shown to the user, used alongside iteration_count for precise scheduling.'
+ ),
+ iteration_start_dates: zod.array(zod.iso.datetime({ offset: true }).nullable()).nullish(),
+ current_iteration: zod
+ .number()
+ .min(surveysUpdateBodyCurrentIterationMin)
+ .max(surveysUpdateBodyCurrentIterationMax)
+ .nullish(),
+ current_iteration_start_date: zod.iso.datetime({ offset: true }).nullish(),
+ response_sampling_start_date: zod.iso.datetime({ offset: true }).nullish(),
+ response_sampling_interval_type: zod
+ .union([
+ zod.enum(['day', 'week', 'month']).describe('\* `day` - day\n\* `week` - week\n\* `month` - month'),
+ zod.enum(['']),
+ zod.null(),
+ ])
+ .optional(),
+ response_sampling_interval: zod
+ .number()
+ .min(surveysUpdateBodyResponseSamplingIntervalMin)
+ .max(surveysUpdateBodyResponseSamplingIntervalMax)
+ .nullish(),
+ response_sampling_limit: zod
+ .number()
+ .min(surveysUpdateBodyResponseSamplingLimitMin)
+ .max(surveysUpdateBodyResponseSamplingLimitMax)
+ .nullish(),
+ response_sampling_daily_limits: zod.unknown().optional(),
+ enable_partial_responses: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'When at least one question is answered, the response is stored (true). The response is stored when all questions are answered (false).'
+ ),
+ enable_iframe_embedding: zod.boolean().nullish(),
+ base_language: zod
+ .string()
+ .max(surveysUpdateBodyBaseLanguageMax)
+ .optional()
+ .describe(
+ "BCP-47 language code (e.g. 'en', 'es', 'es-MX') describing the language of the survey's untranslated text. Defaults to 'en'. Cannot also appear as a key in `translations`."
+ ),
+ translations: zod.unknown().optional(),
+ _create_in_folder: zod.string().optional(),
+ form_content: zod.unknown().optional(),
+})
export const surveysPartialUpdateBodyNameMax = 400