From b8fed0591824b27b5dce62c6f0d5fca90433ec06 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 16:46:55 -0400
Subject: [PATCH 01/12] Send visible copied next steps to CRM hosts and saved
examples
---
builder-frontend/public/integrations/host.js | 6 +-
.../components/screener/FormRenderer.test.tsx | 50 +++++++
.../src/components/screener/FormRenderer.tsx | 22 +++
.../src/components/screener/Screener.test.tsx | 9 +-
.../src/components/screener/Screener.tsx | 9 +-
.../formJsExtensions/nextSteps/selection.ts | 14 ++
.../printSummary/PrintSummary.ts | 17 +--
.../src/integrations/nextSteps.test.ts | 99 ++++++++++++++
.../src/integrations/nextSteps.ts | 71 ++++++++++
.../src/integrations/screenerBridge.test.ts | 45 +++++++
.../src/integrations/screenerBridge.ts | 10 +-
docs/src/content/docs/dev/crm-integrations.md | 46 ++++++-
e2e/tests/crmIntegration.spec.ts | 126 +++++++++++++++++-
examples/crm/browser/README.md | 12 ++
examples/crm/browser/demo.html | 7 +
examples/crm/browser/demo.js | 71 ++++++++++
examples/crm/salesforce/README.md | 12 ++
.../salesforce/bdtScreening/bdtScreening.js | 1 +
.../bdtScreeningResults.css | 16 +++
.../bdtScreeningResults.html | 35 +++++
.../bdtScreeningResults/formatResults.js | 59 ++++++++
.../salesforce/tests/formatResults.test.mjs | 64 +++++++++
22 files changed, 780 insertions(+), 21 deletions(-)
create mode 100644 builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
create mode 100644 builder-frontend/src/integrations/nextSteps.test.ts
create mode 100644 builder-frontend/src/integrations/nextSteps.ts
create mode 100644 examples/crm/salesforce/tests/formatResults.test.mjs
diff --git a/builder-frontend/public/integrations/host.js b/builder-frontend/public/integrations/host.js
index 91094259..1caa3857 100644
--- a/builder-frontend/public/integrations/host.js
+++ b/builder-frontend/public/integrations/host.js
@@ -143,7 +143,11 @@ export function createCrmIntegration({
message.inputData &&
typeof message.inputData === "object" &&
!Array.isArray(message.inputData) &&
- typeof message.evaluatedAt === "string"
+ typeof message.evaluatedAt === "string" &&
+ (message.nextSteps === undefined ||
+ (message.nextSteps !== null &&
+ typeof message.nextSteps === "object" &&
+ !Array.isArray(message.nextSteps)))
) {
onResult(message);
} else if (
diff --git a/builder-frontend/src/components/screener/FormRenderer.test.tsx b/builder-frontend/src/components/screener/FormRenderer.test.tsx
index c56d6132..a01cc098 100644
--- a/builder-frontend/src/components/screener/FormRenderer.test.tsx
+++ b/builder-frontend/src/components/screener/FormRenderer.test.tsx
@@ -31,6 +31,56 @@ describe("FormRenderer host prefill", () => {
document.body.innerHTML = "";
});
+ it("exports only the currently visible saved content and unregisters on unmount", async () => {
+ const register = vi.fn();
+ const container = document.body.appendChild(document.createElement("div"));
+ dispose = render(
+ () => (
+ ({ show: true })}
+ hiddenQuestionPaths={() => []}
+ submitForm={() => {}}
+ registerNextStepsProvider={register}
+ />
+ ),
+ container,
+ );
+ await vi.waitFor(() => expect(register).toHaveBeenCalledOnce());
+ const results = {
+ benefit: { name: "Benefit", result: "TRUE" as const, check_results: {} },
+ };
+ const provider = register.mock.calls[0][0];
+ expect(provider(results).benefit.body.text).toBe("Saved instructions");
+ container
+ .querySelector('input[type="checkbox"]')!
+ .click();
+ await vi.waitFor(() => expect(provider(results)).toBeUndefined());
+ dispose();
+ dispose = undefined;
+ expect(register).toHaveBeenLastCalledWith(undefined);
+ });
+
it("evaluates unknown host answers as null until the user answers them", async () => {
const submitForm = vi.fn();
const container = document.body.appendChild(document.createElement("div"));
diff --git a/builder-frontend/src/components/screener/FormRenderer.tsx b/builder-frontend/src/components/screener/FormRenderer.tsx
index aa42ddaa..6554ad63 100644
--- a/builder-frontend/src/components/screener/FormRenderer.tsx
+++ b/builder-frontend/src/components/screener/FormRenderer.tsx
@@ -11,6 +11,12 @@ import {
connectScreeningResults,
screeningResultsModule,
} from "../screenerEditor/formJsExtensions/screeningResults/screeningResults";
+import { firstVisibleNextSteps } from "../screenerEditor/formJsExtensions/nextSteps/selection";
+import {
+ projectNextSteps,
+ type NextStepsProvider,
+} from "@/integrations/nextSteps";
+import type { ScreeningResultsService } from "../screenerEditor/formJsExtensions/screeningResults/screeningResults";
import type { ScreenerResult } from "@/types";
import { hideQuestions } from "@/utils/questionVotes";
import { normalizeArrayFieldData } from "@/utils/arrayFieldData";
@@ -34,7 +40,9 @@ function FormRenderer({
failed = () => false,
onNextStepsShownChange,
screenerName,
+ registerNextStepsProvider,
}: {
+ registerNextStepsProvider?: (provider: NextStepsProvider | undefined) => void;
schema: { [key: string]: any };
formData: Accessor;
hiddenQuestionPaths: Accessor;
@@ -53,6 +61,7 @@ function FormRenderer({
let form: Form | undefined;
let currentData: any = {};
let importing = false;
+ let disposed = false;
let unknownPaths: string[][] = [];
const evaluationData = (data: any) =>
normalizeArrayFieldData(schema, restoreUnknownAnswers(data, unknownPaths));
@@ -98,6 +107,17 @@ function FormRenderer({
form
.importSchema(hideQuestions(schema, hiddenQuestionPaths()), formData())
.then(() => {
+ if (disposed) return;
+ registerNextStepsProvider?.((results) => {
+ const service =
+ form!.get("screeningResults");
+ const fields =
+ (form!.get("formFieldRegistry") as any).getForm()?.components ?? [];
+ return projectNextSteps(
+ results,
+ firstVisibleNextSteps(fields, service.isNextStepsFieldShown),
+ );
+ });
currentData = cloneDeep(form?._getState().data || formData());
if (evaluateInitialData) {
unknownPaths = findFilledUnknownPaths(formData(), currentData);
@@ -115,6 +135,8 @@ function FormRenderer({
.catch(console.error);
onCleanup(() => {
+ disposed = true;
+ registerNextStepsProvider?.(undefined);
debouncedSubmit.cancel();
form?.destroy();
});
diff --git a/builder-frontend/src/components/screener/Screener.test.tsx b/builder-frontend/src/components/screener/Screener.test.tsx
index 2f819619..a7f8db4c 100644
--- a/builder-frontend/src/components/screener/Screener.test.tsx
+++ b/builder-frontend/src/components/screener/Screener.test.tsx
@@ -55,11 +55,15 @@ vi.mock("./FormRenderer", () => ({
return (
<>
-
+
>
);
},
@@ -115,6 +119,7 @@ describe("published screener integration lifecycle", () => {
expect(integration.result).toHaveBeenLastCalledWith(
{ custom: { householdIncome: 50000 } },
result("FALSE"),
+ undefined,
);
old.resolve(result("TRUE"));
await old.promise;
diff --git a/builder-frontend/src/components/screener/Screener.tsx b/builder-frontend/src/components/screener/Screener.tsx
index e589b013..9c6fa0c4 100644
--- a/builder-frontend/src/components/screener/Screener.tsx
+++ b/builder-frontend/src/components/screener/Screener.tsx
@@ -25,6 +25,7 @@ import {
getUnneededQuestionPaths,
haveSameQuestionPaths,
} from "@/utils/questionVotes";
+import type { NextStepsProvider } from "@/integrations/nextSteps";
import { createScreeningBridge } from "@/integrations/screenerBridge";
export default function Screener() {
@@ -51,6 +52,7 @@ export default function Screener() {
});
const [integrationReady, setIntegrationReady] = createSignal(!bridge);
let evaluationSequence = 0;
+ let nextStepsProvider: NextStepsProvider | undefined;
// Start once the screener loads, so the host's origin can be checked against
// the origins its builder allowed. Only an allowed host gets answers.
let bridgeStarted = false;
@@ -100,10 +102,12 @@ export default function Screener() {
data,
);
if (sequence !== evaluationSequence) return;
+ // Read visible content before setting results can re-import the form to hide questions.
+ const nextSteps = nextStepsProvider?.(evaluationResult);
setScreenerResult(evaluationResult);
setResultsStale(false);
setEvaluationFailed(false);
- bridge?.result(data, evaluationResult);
+ bridge?.result(data, evaluationResult, nextSteps);
} catch (err) {
if (sequence !== evaluationSequence) return;
setEvaluationFailed(true);
@@ -144,6 +148,9 @@ export default function Screener() {
{
+ nextStepsProvider = provider;
+ }}
screenerName={() => screener()?.screenerName ?? ""}
schema={screener()?.formSchema || {}}
formData={formData}
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
new file mode 100644
index 00000000..5579de5c
--- /dev/null
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
@@ -0,0 +1,14 @@
+import type { NextStepsField } from "./NextSteps";
+import { NEXT_STEPS_TYPE } from "./content";
+
+/** Shared by print and CRM exports: use the first rendered component in schema order. */
+export function firstVisibleNextSteps(
+ fields: any[],
+ isShown: (id: string) => boolean,
+): NextStepsField | undefined {
+ for (const field of fields) {
+ if (field.type === NEXT_STEPS_TYPE && isShown(field.id)) return field;
+ const nested = firstVisibleNextSteps(field.components ?? [], isShown);
+ if (nested) return nested;
+ }
+}
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
index 48c3d046..f003e180 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
@@ -3,7 +3,8 @@ import { render } from "preact";
import { useContext, useLayoutEffect, useRef, useState } from "preact/hooks";
import { FormContext, iconsByType, Text } from "@bpmn-io/form-js-viewer";
import { NextStepsBody, type NextStepsField } from "../nextSteps/NextSteps";
-import { NEXT_STEPS_TYPE, webLink } from "../nextSteps/content";
+import { webLink } from "../nextSteps/content";
+import { firstVisibleNextSteps } from "../nextSteps/selection";
import type { ScreeningResultsService } from "../screeningResults/screeningResults";
import { useScreeningResults } from "../screeningResults/useScreeningResults";
import "./printSummary.css";
@@ -74,20 +75,10 @@ export function PrintSummary() {
const benefits = Object.entries(current.results ?? {});
setError("");
// Print what the person sees: skip Next steps hidden by a condition.
- const firstNextSteps = (fields: any[]): NextStepsField | undefined => {
- for (const field of fields) {
- if (
- field.type === NEXT_STEPS_TYPE &&
- service.isNextStepsFieldShown(field.id)
- )
- return field;
- const nested = firstNextSteps(field.components ?? []);
- if (nested) return nested;
- }
- };
const source: NextStepsField =
- firstNextSteps(
+ firstVisibleNextSteps(
context.getService("formFieldRegistry").getForm()?.components ?? [],
+ service.isNextStepsFieldShown,
) ?? {};
const root = document.createElement("article");
root.className = "bdt-print-root";
diff --git a/builder-frontend/src/integrations/nextSteps.test.ts b/builder-frontend/src/integrations/nextSteps.test.ts
new file mode 100644
index 00000000..6ba5f5ab
--- /dev/null
+++ b/builder-frontend/src/integrations/nextSteps.test.ts
@@ -0,0 +1,99 @@
+import { expect, it } from "vitest";
+import { projectNextSteps } from "./nextSteps";
+import type { ScreenerResult } from "@/types";
+
+const results: ScreenerResult = {
+ housing: { name: "Housing", result: "TRUE", check_results: {} },
+ food: {
+ name: "Food",
+ result: "FALSE",
+ check_results: {
+ a: { result: "FALSE", name: "Income", aliasName: "Income limit" } as any,
+ b: { result: "FALSE", name: "Residence", aliasName: " " } as any,
+ c: { result: "TRUE", name: "Other requirement" } as any,
+ },
+ },
+ utility: {
+ name: "Utilities",
+ result: "UNABLE_TO_DETERMINE",
+ check_results: {},
+ },
+};
+const field = {
+ benefitContent: {
+ housing: {
+ eligible: {
+ applyUrl: "https://example.org/apply",
+ helpUrl: "https://example.org/help",
+ helpPhone: " 215-555-0100 ",
+ body: "Bring **ID**.",
+ },
+ ineligible: { note: "Not for eligible" },
+ },
+ food: {
+ eligible: { applyUrl: "https://example.org/wrong" },
+ ineligible: { note: "Ask about **other help**." },
+ },
+ removed: { eligible: { body: "Removed instructions" } },
+ },
+};
+
+it("exports only decided benefits and the content matching each outcome", () => {
+ const copy = structuredClone(field);
+ expect(projectNextSteps(results, field)).toEqual({
+ housing: {
+ status: "eligible",
+ applyUrl: "https://example.org/apply",
+ help: { url: "https://example.org/help", phone: "215-555-0100" },
+ body: { format: "markdown", text: "Bring **ID**." },
+ unmetRequirements: [],
+ note: null,
+ },
+ food: {
+ status: "ineligible",
+ applyUrl: null,
+ help: { url: null, phone: null },
+ body: null,
+ unmetRequirements: ["Income limit", "Residence"],
+ note: { format: "markdown", text: "Ask about **other help**." },
+ },
+ });
+ expect(field).toEqual(copy);
+});
+
+it("omits the extension without a visible field and respects whenComplete", () => {
+ expect(projectNextSteps(results)).toBeUndefined();
+ expect(
+ projectNextSteps(results, { ...field, showWhen: "whenComplete" }),
+ ).toEqual({});
+ expect(
+ Object.keys(
+ projectNextSteps(
+ { housing: results.housing },
+ { ...field, showWhen: "whenComplete" },
+ )!,
+ ),
+ ).toEqual(["housing"]);
+});
+
+it("does not invent missing content or pass unsafe application links", () => {
+ const exported = projectNextSteps(results, {
+ benefitContent: {
+ housing: {
+ eligible: {
+ applyUrl: "javascript:alert(1)",
+ helpUrl: "https://user:secret@example.org/",
+ },
+ },
+ },
+ })!;
+ expect(exported.housing).toEqual({
+ status: "eligible",
+ applyUrl: null,
+ help: { url: null, phone: null },
+ body: null,
+ unmetRequirements: [],
+ note: null,
+ });
+ expect(exported.food.note).toBeNull();
+});
diff --git a/builder-frontend/src/integrations/nextSteps.ts b/builder-frontend/src/integrations/nextSteps.ts
new file mode 100644
index 00000000..f04c4d41
--- /dev/null
+++ b/builder-frontend/src/integrations/nextSteps.ts
@@ -0,0 +1,71 @@
+import type { ScreenerResult } from "@/types";
+import type { NextStepsField } from "@/components/screenerEditor/formJsExtensions/nextSteps/NextSteps";
+import { webLink } from "@/components/screenerEditor/formJsExtensions/nextSteps/content";
+
+type Markdown = { format: "markdown"; text: string };
+export type CrmNextSteps = Record<
+ string,
+ {
+ status: "eligible" | "ineligible";
+ applyUrl: string | null;
+ help: { url: string | null; phone: string | null };
+ body: Markdown | null;
+ unmetRequirements: string[];
+ note: Markdown | null;
+ }
+>;
+export type NextStepsProvider = (
+ results: ScreenerResult,
+) => CrmNextSteps | undefined;
+
+const text = (value?: string | null) =>
+ typeof value === "string" && value.trim() ? value : null;
+const markdown = (value?: string | null): Markdown | null =>
+ text(value) ? { format: "markdown", text: value! } : null;
+
+/** Project the saved screener copy, never evaluation-provider content or generated HTML. */
+export function projectNextSteps(
+ results: ScreenerResult,
+ field?: NextStepsField,
+): CrmNextSteps | undefined {
+ if (!field) return;
+ const benefits = Object.entries(results);
+ if (
+ field.showWhen === "whenComplete" &&
+ benefits.some(([, benefit]) => !["TRUE", "FALSE"].includes(benefit.result))
+ )
+ return {};
+ return Object.fromEntries(
+ benefits.flatMap(([id, benefit]) => {
+ if (!["TRUE", "FALSE"].includes(benefit.result)) return [];
+ const content = field.benefitContent?.[id];
+ const eligible = benefit.result === "TRUE";
+ return [
+ [
+ id,
+ {
+ status: eligible ? "eligible" : "ineligible",
+ applyUrl: eligible
+ ? (webLink(content?.eligible?.applyUrl) ?? null)
+ : null,
+ help: {
+ url: eligible
+ ? (webLink(content?.eligible?.helpUrl) ?? null)
+ : null,
+ phone: eligible
+ ? (text(content?.eligible?.helpPhone)?.trim() ?? null)
+ : null,
+ },
+ body: eligible ? markdown(content?.eligible?.body) : null,
+ unmetRequirements: eligible
+ ? []
+ : Object.values(benefit.check_results ?? {})
+ .filter((check) => check.result === "FALSE")
+ .map((check) => check.aliasName?.trim() || check.name),
+ note: eligible ? null : markdown(content?.ineligible?.note),
+ },
+ ],
+ ];
+ }),
+ );
+}
diff --git a/builder-frontend/src/integrations/screenerBridge.test.ts b/builder-frontend/src/integrations/screenerBridge.test.ts
index f599f422..5690c9df 100644
--- a/builder-frontend/src/integrations/screenerBridge.test.ts
+++ b/builder-frontend/src/integrations/screenerBridge.test.ts
@@ -79,6 +79,51 @@ afterEach(() => {
});
describe("published screener CRM bridge", () => {
+ it.each([false, true])(
+ "round-trips optional next steps without changing protocol version (JSON=%s)",
+ (serializeMessages) => {
+ const s = setup();
+ const onResult = vi.fn();
+ const host = createCrmIntegration({
+ screenerUrl: "https://bdt.example/screener/published-id",
+ getTargetWindow: () => s.child as any,
+ initialData: {},
+ requestId: "request-1",
+ serializeMessages,
+ onResult,
+ hostWindow: s.host as any,
+ });
+ s.bridge.start();
+ s.receive(s.hostPost.mock.calls[0][0]);
+ s.send(s.childPost.mock.calls[0][0]);
+ s.receive(s.hostPost.mock.calls[1][0]);
+ const nextSteps = {
+ benefit: {
+ status: "eligible" as const,
+ applyUrl: null,
+ help: { url: null, phone: null },
+ body: { format: "markdown" as const, text: "Bring **ID**." },
+ unmetRequirements: [],
+ note: null,
+ },
+ };
+ s.bridge.result({}, results, nextSteps);
+ s.receive(s.hostPost.mock.lastCall![0]);
+ expect(onResult).toHaveBeenLastCalledWith(
+ expect.objectContaining({ version: 1, nextSteps }),
+ );
+ const last = serializeMessages
+ ? JSON.parse(s.hostPost.mock.lastCall![0])
+ : s.hostPost.mock.lastCall![0];
+ s.receive({ ...last, nextSteps: [] });
+ expect(onResult).toHaveBeenCalledOnce();
+ s.bridge.result({}, results);
+ s.receive(s.hostPost.mock.lastCall![0]);
+ expect(onResult.mock.lastCall![0]).not.toHaveProperty("nextSteps");
+ host.dispose();
+ s.bridge.dispose();
+ },
+ );
it("repeats ready until a host initializes it", () => {
const s = setup();
s.bridge.start();
diff --git a/builder-frontend/src/integrations/screenerBridge.ts b/builder-frontend/src/integrations/screenerBridge.ts
index 574620fd..a6d80f1a 100644
--- a/builder-frontend/src/integrations/screenerBridge.ts
+++ b/builder-frontend/src/integrations/screenerBridge.ts
@@ -1,5 +1,6 @@
import type { ScreenerResult } from "@/types";
import { isUnsafeObjectKey } from "@/utils/unsafeObjectKeys";
+import type { CrmNextSteps } from "./nextSteps";
const CHANNEL = "bdt.crm";
const VERSION = 1;
@@ -28,7 +29,11 @@ export interface ScreeningBridge {
readonly origin: string;
start(): void;
dispose(): void;
- result(inputData: Record, results: ScreenerResult): void;
+ result(
+ inputData: Record,
+ results: ScreenerResult,
+ nextSteps?: CrmNextSteps,
+ ): void;
error(): void;
/** Call before start(): answer the host's initialize with this error, then stop. */
fail(code: ConnectionFailure): void;
@@ -169,11 +174,12 @@ export function createScreeningBridge(
}, CONNECT_TIMEOUT_MS);
},
dispose,
- result(inputData, results) {
+ result(inputData, results, nextSteps) {
if (requestId)
send("result", {
inputData,
results,
+ ...(nextSteps === undefined ? {} : { nextSteps }),
evaluatedAt: new Date().toISOString(),
});
},
diff --git a/docs/src/content/docs/dev/crm-integrations.md b/docs/src/content/docs/dev/crm-integrations.md
index 299aa779..f8418bdc 100644
--- a/docs/src/content/docs/dev/crm-integrations.md
+++ b/docs/src/content/docs/dev/crm-integrations.md
@@ -101,6 +101,7 @@ const connection = createCrmIntegration({
screenerId: message.screenerId,
evaluatedAt: message.evaluatedAt,
results: message.results,
+ nextSteps: message.nextSteps,
});
},
onError: () => showEvaluationError(),
@@ -181,10 +182,53 @@ Every message is a plain object with these envelope fields:
| Screener → host | `ready` | Repeated until initialized; send prefill for this `sessionId` |
| Host → screener | `initialize` | `inputData`: a JSON form-data object; use `{}` for no prefill |
| Screener → host | `initialized` | Prefill accepted; form loads and evaluates |
-| Screener → host | `result` | `inputData`, `results`, `evaluatedAt` (ISO 8601 timestamp) |
+| Screener → host | `result` | `inputData`, `results`, `evaluatedAt` (ISO 8601 timestamp), optional `nextSteps` |
| Screener → host | `error` | `code`: see below |
| Host → screener | `disconnect` | Host closed the connection; screener stops and says so |
+### Next steps in result messages
+
+Version 1 includes an optional, additive `nextSteps` field. Existing hosts may
+ignore it; no protocol version change or new handshake is required. The host
+adapter forwards the field unchanged in both object and JSON message modes.
+
+```json
+{
+ "nextSteps": {
+ "benefit-id": {
+ "status": "eligible",
+ "applyUrl": "https://example.org/apply",
+ "help": { "url": "https://example.org/help", "phone": "215-555-0100" },
+ "body": { "format": "markdown", "text": "Bring **proof of residence**." },
+ "unmetRequirements": [],
+ "note": null
+ }
+ }
+}
+```
+
+Only decided benefits are included, keyed by their evaluation benefit IDs.
+Eligible entries contain application/help contacts and `body`; ineligible entries
+have `status: "ineligible"`, `unmetRequirements` (the failed checks' display names),
+and `note` with the same `{ format: "markdown", text }` structure. Unused contacts
+and text fields are `null`; unused requirements are an empty array. Missing
+instructions remain empty rather than being invented.
+
+Content comes from the first **visible** Next steps component in schema order,
+including nested groups, just like printing. It uses the screener's saved copy,
+not current benefit defaults or content in an evaluation response. Hidden
+components are skipped. If none is visible, `nextSteps` is omitted. If the
+component uses `whenComplete`, `nextSteps` is `{}` until every benefit is decided.
+As with `results`, each new message replaces the previous snapshot: an omitted
+field or empty object must clear any previous instructions in the host.
+
+The payload contains structured data, never rendered HTML. Treat Markdown as
+untrusted content: display it as plain text (as the examples do), or use a
+sanitizing Markdown renderer. Validate links before making them clickable. The
+screener emits only HTTP(S) application/help URLs, but hosts must still validate
+any saved snapshot they read. Save `nextSteps` alongside `results` only when the
+user chooses to save; the protocol does not change persistence authorization.
+
The screener repeats `ready` about every 500 ms until it's initialized, so a
host that starts listening late still connects. Ignore repeated `ready` messages
for a session you've already initialized. If nothing initializes the screener
diff --git a/e2e/tests/crmIntegration.spec.ts b/e2e/tests/crmIntegration.spec.ts
index bad4d2e1..fb147a14 100644
--- a/e2e/tests/crmIntegration.spec.ts
+++ b/e2e/tests/crmIntegration.spec.ts
@@ -6,6 +6,9 @@ let demoServer: ChildProcess | undefined;
let demoUrl: string;
// Origins the mocked published screener allows; the demo's by default.
let integrationOrigins: string[];
+let includeNextSteps: boolean;
+let hideNextSteps: boolean;
+let showWhen: string;
// Only this spec needs the CRM host example, so it starts its own server on a
// free port instead of making every Playwright project reserve one.
@@ -40,6 +43,9 @@ test.afterAll(() => {
// Public browser integration tests use intercepted API responses, not Firebase.
test.beforeEach(async ({ context }) => {
integrationOrigins = [new URL(demoUrl).origin];
+ includeNextSteps = true;
+ hideNextSteps = false;
+ showWhen = "whenDecided";
await context.route("**/api/published/**", async (route) => {
const request = route.request();
const headers = {
@@ -84,6 +90,31 @@ test.beforeEach(async ({ context }) => {
key: "custom.wantsExtraCash",
label: "Interested in cash assistance",
},
+ ...(includeNextSteps
+ ? [
+ {
+ id: "next",
+ type: "next_steps",
+ showWhen,
+ conditional: {
+ hide: hideNextSteps
+ ? "=true"
+ : "=not(custom.wantsExtraCash)",
+ },
+ benefitContent: {
+ benefit: {
+ eligible: {
+ applyUrl: "https://example.org/apply",
+ helpUrl: "https://example.org/help",
+ helpPhone: "215-555-0100",
+ body: "Screener-specific application instructions.",
+ },
+ ineligible: { note: "Ask about other assistance." },
+ },
+ },
+ },
+ ]
+ : []),
],
},
},
@@ -96,7 +127,18 @@ test.beforeEach(async ({ context }) => {
benefit: {
name: "Example benefit",
result: input.custom.householdIncome <= 40000 ? "TRUE" : "FALSE",
- check_results: {},
+ check_results:
+ input.custom.householdIncome <= 40000
+ ? {}
+ : {
+ income: {
+ name: "Income",
+ aliasName: "Income must be below $40,000",
+ result: "FALSE",
+ inputPaths: [],
+ parameters: {},
+ },
+ },
},
},
});
@@ -208,6 +250,15 @@ for (const serializeMessages of [false, true]) {
await expect(
record.getByText("Ineligible", { exact: true }),
).toBeVisible();
+ await expect(
+ record.getByText("Ask about other assistance.", { exact: true }),
+ ).toBeVisible();
+ await expect(
+ record.getByText("Income must be below $40,000", { exact: true }),
+ ).toBeVisible();
+ await expect(
+ record.getByRole("link", { name: "Apply for this benefit" }),
+ ).toHaveCount(0);
await expect(record.locator("#saved-screener")).toHaveText("crm-test");
await expect(record.locator("#saved-at")).toHaveAttribute(
"datetime",
@@ -246,6 +297,29 @@ for (const serializeMessages of [false, true]) {
).toBeVisible();
await page.locator("#save").click();
await expect(record.getByText("Eligible", { exact: true })).toBeVisible();
+ await expect(
+ record.getByText("Screener-specific application instructions.", {
+ exact: true,
+ }),
+ ).toBeVisible();
+ await expect(
+ record.getByRole("link", { name: "Apply for this benefit" }),
+ ).toHaveAttribute("href", "https://example.org/apply");
+ // Hiding the component omits the extension; explicitly saving replaces old instructions.
+ await screener.getByLabel("Interested in cash assistance").uncheck();
+ await expect(page.locator("#save")).toBeEnabled();
+ await page.locator("#save").click();
+ await expect(
+ record.getByText("Screener-specific application instructions.", {
+ exact: true,
+ }),
+ ).toHaveCount(0);
+ const stored = await page.evaluate(
+ () =>
+ JSON.parse(localStorage.getItem("bdt.crm.browser-demo.record.v1")!)
+ .screening,
+ );
+ expect(stored).not.toHaveProperty("nextSteps");
const savedAt = await record
.locator("#saved-at")
.getAttribute("datetime");
@@ -316,3 +390,53 @@ test("standalone screener still evaluates edited answers", async ({ page }) => {
await page.getByLabel("Household income").fill("30000");
await expect(page.getByText("Eligible", { exact: true })).toBeVisible();
});
+
+for (const scenario of ["absent", "hidden", "whenComplete"] as const) {
+ test(`CRM next steps are omitted or empty when ${scenario}`, async ({
+ page,
+ baseURL,
+ context,
+ }) => {
+ includeNextSteps = scenario !== "absent";
+ hideNextSteps = scenario === "hidden";
+ showWhen = scenario === "whenComplete" ? "whenComplete" : "whenDecided";
+ if (scenario === "whenComplete")
+ await context.route(
+ "**/api/published/crm-test/evaluate",
+ async (route) => {
+ if (route.request().method() !== "POST") return route.fallback();
+ await route.fulfill({
+ headers: { "Access-Control-Allow-Origin": "*" },
+ json: {
+ benefit: {
+ name: "Example benefit",
+ result: "TRUE",
+ check_results: {},
+ },
+ utility: {
+ name: "Utility help",
+ result: "UNABLE_TO_DETERMINE",
+ check_results: {},
+ },
+ },
+ });
+ },
+ );
+ await page.goto(demoUrl);
+ await page
+ .locator("#screener-url")
+ .fill(new URL("/screener/crm-test", baseURL).href);
+ await page.locator("#monthly-income").fill("2000");
+ await page.locator("#cash-interest").selectOption("requested");
+ await page.locator("#embed").click();
+ await expect(page.locator("#save")).toBeEnabled({ timeout: 15000 });
+ await page.locator("#save").click();
+ const stored = await page.evaluate(
+ () =>
+ JSON.parse(localStorage.getItem("bdt.crm.browser-demo.record.v1")!)
+ .screening,
+ );
+ if (scenario === "whenComplete") expect(stored.nextSteps).toEqual({});
+ else expect(stored).not.toHaveProperty("nextSteps");
+ });
+}
diff --git a/examples/crm/browser/README.md b/examples/crm/browser/README.md
index 937efbde..74592720 100644
--- a/examples/crm/browser/README.md
+++ b/examples/crm/browser/README.md
@@ -81,3 +81,15 @@ already running. Restart a manually running example server after adding assets.
The tests verify that flat client fields reach the screener as mapped nested data,
including monthly-to-annual income conversion. They intercept published API responses, so they require no
Firebase emulators, login, published screener, or CRM account.
+
+## Saved next steps
+
+New result messages may include `nextSteps` alongside `results`. The example
+saves both on the user's explicit Save action and shows application/help links,
+contact numbers, instructions, and unmet requirements from that snapshot.
+Markdown is displayed as plain text rather than inserted as HTML. Links accept
+only HTTP(S) destinations without embedded credentials. Older saved records
+without `nextSteps` continue to display their benefit decisions.
+
+Only visible screener content is sent. A missing `nextSteps` field or `{}` in a
+new snapshot clears previous instructions; it does not mean to keep stale ones.
diff --git a/examples/crm/browser/demo.html b/examples/crm/browser/demo.html
index f67f6a81..f1ffe3b7 100644
--- a/examples/crm/browser/demo.html
+++ b/examples/crm/browser/demo.html
@@ -156,6 +156,13 @@
border: 1px solid #dce2ed;
border-radius: 8px;
}
+ .instructions {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ }
+ .benefit a {
+ overflow-wrap: anywhere;
+ }
.benefit h3 {
font-size: 1rem;
margin-bottom: 0.75rem;
diff --git a/examples/crm/browser/demo.js b/examples/crm/browser/demo.js
index 05986fee..0cb6d09a 100644
--- a/examples/crm/browser/demo.js
+++ b/examples/crm/browser/demo.js
@@ -76,6 +76,67 @@ function renderTime(id, value) {
}
}
+// Render Markdown as plain text in this dependency-free demo; never inject HTML.
+function appendNextSteps(item, steps, outcome) {
+ if (
+ !steps ||
+ !["eligible", "ineligible"].includes(outcome) ||
+ steps.status !== outcome
+ )
+ return;
+ const section = document.createElement("section");
+ section.setAttribute("aria-label", "Saved next steps");
+ const paragraph = (value) => {
+ if (typeof value !== "string" || !value.trim()) return;
+ const p = document.createElement("p");
+ p.className = "instructions";
+ p.textContent = value;
+ section.append(p);
+ };
+ const link = (value, label) => {
+ if (typeof value !== "string") return;
+ try {
+ const url = new URL(value);
+ if (
+ !["http:", "https:"].includes(url.protocol) ||
+ url.username ||
+ url.password
+ )
+ return;
+ const a = document.createElement("a");
+ a.href = url.href;
+ a.textContent = label;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer";
+ const p = document.createElement("p");
+ p.append(a);
+ section.append(p);
+ } catch {
+ /* Ignore invalid saved URLs. */
+ }
+ };
+ if (outcome === "eligible") {
+ link(steps.applyUrl, "Apply for this benefit");
+ link(steps.help?.url, "Get help");
+ if (typeof steps.help?.phone === "string")
+ paragraph(`Help phone: ${steps.help.phone}`);
+ if (steps.body?.format === "markdown") paragraph(steps.body.text);
+ } else {
+ if (Array.isArray(steps.unmetRequirements)) {
+ const list = document.createElement("ul");
+ for (const requirement of steps.unmetRequirements) {
+ if (typeof requirement !== "string") continue;
+ const li = document.createElement("li");
+ li.textContent = requirement;
+ list.append(li);
+ }
+ section.append(list);
+ }
+ if (steps.note?.format === "markdown") paragraph(steps.note.text);
+ }
+ item.append(section);
+}
+
function renderRecord() {
// Read the stored record, rather than displaying the latest unsaved message.
const snapshot = readRecord().screening;
@@ -106,6 +167,15 @@ function renderRecord() {
status.className = `outcome ${outcome.style}`;
status.textContent = outcome.label;
item.append(name, status);
+ appendNextSteps(
+ item,
+ snapshot.nextSteps?.[id],
+ benefit.result === "TRUE"
+ ? "eligible"
+ : benefit.result === "FALSE"
+ ? "ineligible"
+ : "unknown",
+ );
element("saved-results").append(item);
}
}
@@ -182,6 +252,7 @@ element("save").addEventListener("click", () => {
evaluatedAt: latest.evaluatedAt,
savedAt: new Date().toISOString(),
results: latest.results,
+ nextSteps: latest.nextSteps,
},
}),
);
diff --git a/examples/crm/salesforce/README.md b/examples/crm/salesforce/README.md
index 3e94bc71..ace8f8c1 100644
--- a/examples/crm/salesforce/README.md
+++ b/examples/crm/salesforce/README.md
@@ -120,3 +120,15 @@ Salesforce references:
- [Objects proxied by Lightning Web Security](https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-proxies.html)
- [Iframe access with Lightning Web Security](https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-iframes.html)
- [Trusted URLs and third-party JavaScript](https://developer.salesforce.com/docs/platform/lwc/guide/js-api-calls)
+
+## Saved next steps
+
+New result messages may include `nextSteps` alongside `results`. The example
+saves both on the user's explicit Save action and shows application/help links,
+contact numbers, instructions, and unmet requirements from that snapshot.
+Markdown is displayed as plain text rather than inserted as HTML. Links accept
+only HTTP(S) destinations without embedded credentials. Older saved records
+without `nextSteps` continue to display their benefit decisions.
+
+Only visible screener content is sent. A missing `nextSteps` field or `{}` in a
+new snapshot clears previous instructions; it does not mean to keep stale ones.
diff --git a/examples/crm/salesforce/bdtScreening/bdtScreening.js b/examples/crm/salesforce/bdtScreening/bdtScreening.js
index 65f6331c..640b16e2 100644
--- a/examples/crm/salesforce/bdtScreening/bdtScreening.js
+++ b/examples/crm/salesforce/bdtScreening/bdtScreening.js
@@ -146,6 +146,7 @@ export default class BdtScreening extends LightningElement {
requestId: message.requestId,
evaluatedAt: message.evaluatedAt,
results: message.results,
+ nextSteps: message.nextSteps,
});
if (snapshot.length > 131072) {
this.status =
diff --git a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css
index 4a1fae69..70dc3831 100644
--- a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css
+++ b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.css
@@ -124,3 +124,19 @@
font-size: 0.75rem;
overflow-wrap: anywhere;
}
+
+.next-steps {
+ margin-top: 0.75rem;
+ overflow-wrap: anywhere;
+}
+.next-steps h4 {
+ font-weight: 600;
+}
+.next-steps p {
+ margin-top: 0.5rem;
+ white-space: pre-wrap;
+}
+.next-steps ul {
+ list-style: disc;
+ padding-left: 1.25rem;
+}
diff --git a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html
index 17745c92..d0fef037 100644
--- a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html
+++ b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html
@@ -32,6 +32,41 @@
{benefit.name}
{benefit.status}
+
+
+ Next steps
+
+
+
+
+
+
+
+ Help phone:
+
+
+
+
+
+
+ - {requirement.name}
+
+
+
+
+
+
+
{benefit.checksLabel}
diff --git a/examples/crm/salesforce/bdtScreeningResults/formatResults.js b/examples/crm/salesforce/bdtScreeningResults/formatResults.js
index 895f3873..9a0b9161 100644
--- a/examples/crm/salesforce/bdtScreeningResults/formatResults.js
+++ b/examples/crm/salesforce/bdtScreeningResults/formatResults.js
@@ -28,6 +28,64 @@ function checkName(check) {
.trim();
}
+function safeUrl(value) {
+ if (typeof value !== "string") return null;
+ try {
+ const url = new URL(value);
+ return ["http:", "https:"].includes(url.protocol) &&
+ !url.username &&
+ !url.password
+ ? url.href
+ : null;
+ } catch {
+ return null;
+ }
+}
+function markdownText(value) {
+ return isObject(value) &&
+ value.format === "markdown" &&
+ typeof value.text === "string"
+ ? value.text
+ : "";
+}
+function nextStepsView(steps, result) {
+ if (
+ !isObject(steps) ||
+ (result !== "TRUE" && result !== "FALSE") ||
+ steps.status !== (result === "TRUE" ? "eligible" : "ineligible")
+ )
+ return {};
+ const eligible = result === "TRUE";
+ const applyUrl = eligible ? safeUrl(steps.applyUrl) : null;
+ const helpUrl = eligible ? safeUrl(steps.help?.url) : null;
+ const phone =
+ eligible && typeof steps.help?.phone === "string" ? steps.help.phone : "";
+ const body = eligible ? markdownText(steps.body) : "";
+ const note = eligible ? "" : markdownText(steps.note);
+ const unmetRequirements =
+ !eligible && Array.isArray(steps.unmetRequirements)
+ ? steps.unmetRequirements
+ .filter((item) => typeof item === "string")
+ .map((name, index) => ({ id: String(index), name }))
+ : [];
+ return {
+ hasNextSteps: !!(
+ applyUrl ||
+ helpUrl ||
+ phone ||
+ body ||
+ note ||
+ unmetRequirements.length
+ ),
+ applyUrl,
+ helpUrl,
+ phone,
+ body,
+ note,
+ unmetRequirements,
+ };
+}
+
export function formatSavedResults(raw) {
const snapshot = JSON.parse(raw);
if (!isObject(snapshot) || !isObject(snapshot.results))
@@ -64,6 +122,7 @@ export function formatSavedResults(raw) {
checks,
hasChecks: checks.length > 0,
checksLabel: `View checks (${checks.length})`,
+ ...nextStepsView(snapshot.nextSteps?.[id], benefit.result),
};
});
const timestamp =
diff --git a/examples/crm/salesforce/tests/formatResults.test.mjs b/examples/crm/salesforce/tests/formatResults.test.mjs
new file mode 100644
index 00000000..59fd9e5c
--- /dev/null
+++ b/examples/crm/salesforce/tests/formatResults.test.mjs
@@ -0,0 +1,64 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+const source = await readFile(
+ new URL("../bdtScreeningResults/formatResults.js", import.meta.url),
+ "utf8",
+);
+const { formatSavedResults } = await import(
+ `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`
+);
+const snapshot = {
+ results: {
+ housing: { name: "Housing", result: "TRUE", check_results: {} },
+ food: { name: "Food", result: "FALSE", check_results: {} },
+ utility: {
+ name: "Utilities",
+ result: "UNABLE_TO_DETERMINE",
+ check_results: {},
+ },
+ },
+ nextSteps: {
+ housing: {
+ status: "eligible",
+ applyUrl: "https://example.org/apply",
+ help: { url: "https://example.org/help", phone: "215-555-0100" },
+ body: { format: "markdown", text: "Bring **ID**." },
+ },
+ food: {
+ status: "ineligible",
+ unmetRequirements: ["Income limit"],
+ note: { format: "markdown", text: "Ask about other help." },
+ },
+ utility: { status: "eligible", applyUrl: "https://example.org/wrong" },
+ },
+};
+
+test("formats saved contacts, instructions and requirements while excluding undecided benefits", () => {
+ const view = formatSavedResults(JSON.stringify(snapshot));
+ assert.equal(view.benefits[0].applyUrl, "https://example.org/apply");
+ assert.equal(view.benefits[0].body, "Bring **ID**.");
+ assert.equal(view.benefits[0].phone, "215-555-0100");
+ assert.deepEqual(view.benefits[1].unmetRequirements, [
+ { id: "0", name: "Income limit" },
+ ]);
+ assert.equal(view.benefits[1].note, "Ask about other help.");
+ assert.equal(view.benefits[2].hasNextSteps, undefined);
+});
+test("reads older snapshots and drops unsafe links without interpreting Markdown", () => {
+ const old = structuredClone(snapshot);
+ delete old.nextSteps;
+ assert.equal(
+ formatSavedResults(JSON.stringify(old)).benefits[0].hasNextSteps,
+ undefined,
+ );
+ const unsafe = structuredClone(snapshot);
+ unsafe.nextSteps.housing.applyUrl = "javascript:alert(1)";
+ unsafe.nextSteps.housing.help.url = "https://user:secret@example.org/";
+ unsafe.nextSteps.housing.body.text = "";
+ const view = formatSavedResults(JSON.stringify(unsafe));
+ assert.equal(view.benefits[0].applyUrl, null);
+ assert.equal(view.benefits[0].helpUrl, null);
+ assert.equal(view.benefits[0].body, "");
+});
From c5d19cfa35feef85666761c6cf660995dde51444 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:04:03 -0400
Subject: [PATCH 02/12] Deliver results when the host gets a malformed
nextSteps
The optional field gated the required message, so a null or array
nextSteps left the CRM waiting with no result or error.
Co-Authored-By: Claude Opus 5.5
---
builder-frontend/public/integrations/host.js | 17 +++++++++++------
.../src/integrations/screenerBridge.test.ts | 11 +++++++++--
docs/src/content/docs/dev/crm-integrations.md | 4 +++-
3 files changed, 23 insertions(+), 9 deletions(-)
diff --git a/builder-frontend/public/integrations/host.js b/builder-frontend/public/integrations/host.js
index 1caa3857..fcb889af 100644
--- a/builder-frontend/public/integrations/host.js
+++ b/builder-frontend/public/integrations/host.js
@@ -143,13 +143,18 @@ export function createCrmIntegration({
message.inputData &&
typeof message.inputData === "object" &&
!Array.isArray(message.inputData) &&
- typeof message.evaluatedAt === "string" &&
- (message.nextSteps === undefined ||
- (message.nextSteps !== null &&
- typeof message.nextSteps === "object" &&
- !Array.isArray(message.nextSteps)))
+ typeof message.evaluatedAt === "string"
) {
- onResult(message);
+ // nextSteps is optional: drop a malformed one, never the results.
+ const { nextSteps, ...rest } = message;
+ onResult(
+ nextSteps === undefined ||
+ (nextSteps &&
+ typeof nextSteps === "object" &&
+ !Array.isArray(nextSteps))
+ ? message
+ : rest,
+ );
} else if (
message.type === "error" &&
["SCREENER_UNAVAILABLE", "ORIGIN_NOT_ALLOWED"].includes(message.code)
diff --git a/builder-frontend/src/integrations/screenerBridge.test.ts b/builder-frontend/src/integrations/screenerBridge.test.ts
index 5690c9df..2c65a279 100644
--- a/builder-frontend/src/integrations/screenerBridge.test.ts
+++ b/builder-frontend/src/integrations/screenerBridge.test.ts
@@ -115,8 +115,15 @@ describe("published screener CRM bridge", () => {
const last = serializeMessages
? JSON.parse(s.hostPost.mock.lastCall![0])
: s.hostPost.mock.lastCall![0];
- s.receive({ ...last, nextSteps: [] });
- expect(onResult).toHaveBeenCalledOnce();
+ for (const malformed of [[], null, "Bring ID"]) {
+ s.receive(
+ serializeMessages
+ ? JSON.stringify({ ...last, nextSteps: malformed })
+ : { ...last, nextSteps: malformed },
+ );
+ expect(onResult.mock.lastCall![0]).toMatchObject({ results });
+ expect(onResult.mock.lastCall![0]).not.toHaveProperty("nextSteps");
+ }
s.bridge.result({}, results);
s.receive(s.hostPost.mock.lastCall![0]);
expect(onResult.mock.lastCall![0]).not.toHaveProperty("nextSteps");
diff --git a/docs/src/content/docs/dev/crm-integrations.md b/docs/src/content/docs/dev/crm-integrations.md
index f8418bdc..1a83e718 100644
--- a/docs/src/content/docs/dev/crm-integrations.md
+++ b/docs/src/content/docs/dev/crm-integrations.md
@@ -190,7 +190,9 @@ Every message is a plain object with these envelope fields:
Version 1 includes an optional, additive `nextSteps` field. Existing hosts may
ignore it; no protocol version change or new handshake is required. The host
-adapter forwards the field unchanged in both object and JSON message modes.
+adapter forwards the field unchanged in both object and JSON message modes. If
+`nextSteps` isn't an object, the adapter drops that field and still delivers the
+result.
```json
{
From fb6a9db5f4d077686c942ad5e43b719d00ef894d Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:04:32 -0400
Subject: [PATCH 03/12] Save Salesforce decisions without next steps when the
snapshot is too large
Adding nextSteps could push a snapshot that used to fit past the
131072-character field, and then nothing was saved.
Co-Authored-By: Claude Opus 5.5
---
examples/crm/salesforce/README.md | 4 +++-
.../crm/salesforce/bdtScreening/bdtScreening.js | 13 +++++++++++--
2 files changed, 14 insertions(+), 3 deletions(-)
diff --git a/examples/crm/salesforce/README.md b/examples/crm/salesforce/README.md
index ace8f8c1..fcb235f4 100644
--- a/examples/crm/salesforce/README.md
+++ b/examples/crm/salesforce/README.md
@@ -128,7 +128,9 @@ saves both on the user's explicit Save action and shows application/help links,
contact numbers, instructions, and unmet requirements from that snapshot.
Markdown is displayed as plain text rather than inserted as HTML. Links accept
only HTTP(S) destinations without embedded credentials. Older saved records
-without `nextSteps` continue to display their benefit decisions.
+without `nextSteps` continue to display their benefit decisions. If the
+snapshot with `nextSteps` exceeds the field size, the example saves the
+decisions without `nextSteps` and says so.
Only visible screener content is sent. A missing `nextSteps` field or `{}` in a
new snapshot clears previous instructions; it does not mean to keep stale ones.
diff --git a/examples/crm/salesforce/bdtScreening/bdtScreening.js b/examples/crm/salesforce/bdtScreening/bdtScreening.js
index 640b16e2..4c696fb3 100644
--- a/examples/crm/salesforce/bdtScreening/bdtScreening.js
+++ b/examples/crm/salesforce/bdtScreening/bdtScreening.js
@@ -141,13 +141,20 @@ export default class BdtScreening extends LightningElement {
async save() {
if (this.cannotSave) return;
const { recordId, message } = this.latest;
- const snapshot = JSON.stringify({
+ const decisions = {
screenerId: message.screenerId,
requestId: message.requestId,
evaluatedAt: message.evaluatedAt,
results: message.results,
+ };
+ let snapshot = JSON.stringify({
+ ...decisions,
nextSteps: message.nextSteps,
});
+ // Keep the decisions when instructions push the snapshot past the field size.
+ const droppedNextSteps =
+ snapshot.length > 131072 && message.nextSteps !== undefined;
+ if (droppedNextSteps) snapshot = JSON.stringify(decisions);
if (snapshot.length > 131072) {
this.status =
"Results exceed the configured field size; use a related screening object.";
@@ -159,7 +166,9 @@ export default class BdtScreening extends LightningElement {
fields: { Id: recordId, [SCREENING.fieldApiName]: snapshot },
});
if (this.recordId === recordId)
- this.status = "Screening results saved to the client record.";
+ this.status = droppedNextSteps
+ ? "Screening results saved without next steps, which exceed the configured field size."
+ : "Screening results saved to the client record.";
} catch {
if (this.recordId === recordId)
this.status = "Could not save. Check field permissions and try again.";
From 111f5ca9f9dd1d010c55d4f46e755446149d9cf5 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:05:14 -0400
Subject: [PATCH 04/12] Keep unnamed failed checks out of exported unmet
requirements
A failed check with a blank alias and no name became null in the
string array sent to the host.
Co-Authored-By: Claude Opus 5.5
---
builder-frontend/src/integrations/nextSteps.test.ts | 1 +
builder-frontend/src/integrations/nextSteps.ts | 4 +++-
2 files changed, 4 insertions(+), 1 deletion(-)
diff --git a/builder-frontend/src/integrations/nextSteps.test.ts b/builder-frontend/src/integrations/nextSteps.test.ts
index 6ba5f5ab..dcfb4659 100644
--- a/builder-frontend/src/integrations/nextSteps.test.ts
+++ b/builder-frontend/src/integrations/nextSteps.test.ts
@@ -11,6 +11,7 @@ const results: ScreenerResult = {
a: { result: "FALSE", name: "Income", aliasName: "Income limit" } as any,
b: { result: "FALSE", name: "Residence", aliasName: " " } as any,
c: { result: "TRUE", name: "Other requirement" } as any,
+ d: { result: "FALSE", aliasName: " " } as any,
},
},
utility: {
diff --git a/builder-frontend/src/integrations/nextSteps.ts b/builder-frontend/src/integrations/nextSteps.ts
index f04c4d41..d9ce27fb 100644
--- a/builder-frontend/src/integrations/nextSteps.ts
+++ b/builder-frontend/src/integrations/nextSteps.ts
@@ -61,7 +61,9 @@ export function projectNextSteps(
? []
: Object.values(benefit.check_results ?? {})
.filter((check) => check.result === "FALSE")
- .map((check) => check.aliasName?.trim() || check.name),
+ .map((check) => check.aliasName?.trim() || check.name)
+ // An unnamed check has nothing to show the host.
+ .filter((name): name is string => !!name?.trim()),
note: eligible ? null : markdown(content?.ineligible?.note),
},
],
From c6ec1e59342a2e8864f2b5aa4f713abb30a8afa6 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:07:24 -0400
Subject: [PATCH 05/12] Render and export next steps from one shared projection
The field and the CRM export each chose outcome content, links,
phone and unmet requirements, so they could drift and send hosts
instructions the person never saw.
Co-Authored-By: Claude Opus 5.5
---
.../formJsExtensions/nextSteps/NextSteps.ts | 48 +++++++-------
.../formJsExtensions/nextSteps/content.ts | 60 ++++++++++++++++-
.../printSummary/PrintSummary.ts | 6 +-
.../src/integrations/nextSteps.ts | 66 +++----------------
4 files changed, 94 insertions(+), 86 deletions(-)
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts
index 42d91a96..71860c8f 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/NextSteps.ts
@@ -6,13 +6,17 @@ import {
sanitizeHTML,
Text,
} from "@bpmn-io/form-js-viewer";
-import type { BenefitResult, NextSteps as Content } from "@/types";
+import type { BenefitResult } from "@/types";
import { useScreeningResults } from "../screeningResults/useScreeningResults";
import {
NEXT_STEPS_TYPE,
+ benefitNextSteps,
contactLink,
+ isDecided,
+ showsDecided,
webLink,
type BenefitContent,
+ type BenefitNextSteps,
} from "./content";
import "./nextSteps.css";
@@ -56,15 +60,15 @@ function Markdown({
}
function Eligible({
- content,
+ steps,
forPrint,
}: {
- content?: Content;
+ steps: BenefitNextSteps;
forPrint?: boolean;
}) {
- const apply = webLink(content?.eligible?.applyUrl);
- const help = webLink(content?.eligible?.helpUrl);
- const phone = content?.eligible?.helpPhone?.trim();
+ const apply = steps.applyUrl;
+ const help = steps.help.url;
+ const phone = steps.help.phone;
const dial =
phone && /^[+\d\s().-]+$/.test(phone)
? phone.replace(/[^+\d]/g, "")
@@ -86,7 +90,7 @@ function Eligible({
${dial ? html`${phone}` : phone}`}
- <${Markdown} text=${content?.eligible?.body} forPrint=${forPrint} />
+ <${Markdown} text=${steps.body?.text} forPrint=${forPrint} />
`;
}
@@ -105,8 +109,7 @@ export function NextSteps({ field }: { field: NextStepsField }) {
const { results, pending, failed, mode } = useScreeningResults();
const benefits = Object.entries(results ?? {});
const complete =
- benefits.length > 0 &&
- benefits.every(([, benefit]) => ["TRUE", "FALSE"].includes(benefit.result));
+ benefits.length > 0 && benefits.every(([, benefit]) => isDecided(benefit));
// Stays in the DOM so screen readers announce completion, as the page's message did.
return html`
@@ -158,7 +161,10 @@ export function NextStepsBody({
Next steps will appear after screening.
`
: null;
- const hideDecided = field.showWhen === "whenComplete" && !complete;
+ const hideDecided = !showsDecided(
+ field,
+ benefits.map(([, benefit]) => benefit),
+ );
return html`
`}
${benefits.map(([id, benefit]) => {
- const content = field.benefitContent?.[id];
- if (benefit.result === "UNABLE_TO_DETERMINE")
+ const steps = benefitNextSteps(benefit, field.benefitContent?.[id]);
+ if (!steps)
return html`
${benefit.name}
Still needs more information.
`;
if (hideDecided) return null;
- const unmet = Object.values(benefit.check_results ?? {}).filter(
- (check) => check.result === "FALSE",
- );
+ const unmet = steps.unmetRequirements;
return html`
${benefit.name}
- ${benefit.result === "TRUE"
- ? html`<${Eligible} content=${content} forPrint=${forPrint} />`
+ ${steps.status === "eligible"
+ ? html`<${Eligible} steps=${steps} forPrint=${forPrint} />`
: html`
You do not appear to be eligible.
@@ -196,15 +200,9 @@ export function NextStepsBody({
${unmet.length > 0 &&
html`
Requirements not met
- ${unmet.map(
- (check) =>
- html`- ${check.aliasName?.trim() || check.name}
`,
- )}
+ ${unmet.map((name) => html`- ${name}
`)}
`}
- <${Markdown}
- text=${content?.ineligible?.note}
- forPrint=${forPrint}
- />
+ <${Markdown} text=${steps.note?.text} forPrint=${forPrint} />
`}
`;
})}
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts
index e9b998cc..6efb80f6 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/content.ts
@@ -1,6 +1,7 @@
import cloneDeep from "lodash/cloneDeep";
-import type { Benefit, NextSteps } from "@/types";
+import type { Benefit, BenefitResult, NextSteps } from "@/types";
import { normalizeHttpUrl } from "@/utils/httpUrl";
+import type { NextStepsField } from "./NextSteps";
export const NEXT_STEPS_TYPE = "next_steps";
export type BenefitContent = Record;
@@ -41,3 +42,60 @@ export function contactLink(value?: string | null): string | undefined {
/* An invalid contact is omitted. */
}
}
+
+export type Markdown = { format: "markdown"; text: string };
+/** A decided benefit's Next steps, as the field shows them and CRM hosts receive them. */
+export type BenefitNextSteps = {
+ status: "eligible" | "ineligible";
+ applyUrl: string | null;
+ help: { url: string | null; phone: string | null };
+ body: Markdown | null;
+ unmetRequirements: string[];
+ note: Markdown | null;
+};
+
+export const isDecided = (benefit: BenefitResult) =>
+ benefit.result === "TRUE" || benefit.result === "FALSE";
+
+/** A whenComplete field shows decided benefits only once every benefit is decided. */
+export const showsDecided = (
+ field: NextStepsField,
+ benefits: BenefitResult[],
+) => field.showWhen !== "whenComplete" || benefits.every(isDecided);
+
+const text = (value?: string | null) =>
+ typeof value === "string" && value.trim() ? value : null;
+const markdown = (value?: string | null): Markdown | null =>
+ text(value) ? { format: "markdown", text: value! } : null;
+
+/** Only the saved copy for the benefit's outcome; undefined while undecided. */
+export function benefitNextSteps(
+ benefit: BenefitResult,
+ content?: NextSteps,
+): BenefitNextSteps | undefined {
+ if (!isDecided(benefit)) return;
+ if (benefit.result === "TRUE")
+ return {
+ status: "eligible",
+ applyUrl: webLink(content?.eligible?.applyUrl) ?? null,
+ help: {
+ url: webLink(content?.eligible?.helpUrl) ?? null,
+ phone: text(content?.eligible?.helpPhone)?.trim() ?? null,
+ },
+ body: markdown(content?.eligible?.body),
+ unmetRequirements: [],
+ note: null,
+ };
+ return {
+ status: "ineligible",
+ applyUrl: null,
+ help: { url: null, phone: null },
+ body: null,
+ unmetRequirements: Object.values(benefit.check_results ?? {})
+ .filter((check) => check.result === "FALSE")
+ .map((check) => check.aliasName?.trim() || check.name)
+ // An unnamed check has nothing to show.
+ .filter((name): name is string => !!name?.trim()),
+ note: markdown(content?.ineligible?.note),
+ };
+}
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
index f003e180..a70e15d5 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
@@ -3,7 +3,7 @@ import { render } from "preact";
import { useContext, useLayoutEffect, useRef, useState } from "preact/hooks";
import { FormContext, iconsByType, Text } from "@bpmn-io/form-js-viewer";
import { NextStepsBody, type NextStepsField } from "../nextSteps/NextSteps";
-import { webLink } from "../nextSteps/content";
+import { isDecided, webLink } from "../nextSteps/content";
import { firstVisibleNextSteps } from "../nextSteps/selection";
import type { ScreeningResultsService } from "../screeningResults/screeningResults";
import { useScreeningResults } from "../screeningResults/useScreeningResults";
@@ -109,9 +109,7 @@ export function PrintSummary() {
<${NextStepsBody}
field=${source}
benefits=${benefits}
- complete=${benefits.every(([, benefit]) =>
- ["TRUE", "FALSE"].includes(benefit.result),
- )}
+ complete=${benefits.every(([, benefit]) => isDecided(benefit))}
pending=${false}
failed=${false}
mode="live"
diff --git a/builder-frontend/src/integrations/nextSteps.ts b/builder-frontend/src/integrations/nextSteps.ts
index d9ce27fb..86edfde5 100644
--- a/builder-frontend/src/integrations/nextSteps.ts
+++ b/builder-frontend/src/integrations/nextSteps.ts
@@ -1,73 +1,27 @@
import type { ScreenerResult } from "@/types";
import type { NextStepsField } from "@/components/screenerEditor/formJsExtensions/nextSteps/NextSteps";
-import { webLink } from "@/components/screenerEditor/formJsExtensions/nextSteps/content";
+import {
+ benefitNextSteps,
+ showsDecided,
+ type BenefitNextSteps,
+} from "@/components/screenerEditor/formJsExtensions/nextSteps/content";
-type Markdown = { format: "markdown"; text: string };
-export type CrmNextSteps = Record<
- string,
- {
- status: "eligible" | "ineligible";
- applyUrl: string | null;
- help: { url: string | null; phone: string | null };
- body: Markdown | null;
- unmetRequirements: string[];
- note: Markdown | null;
- }
->;
+export type CrmNextSteps = Record;
export type NextStepsProvider = (
results: ScreenerResult,
) => CrmNextSteps | undefined;
-const text = (value?: string | null) =>
- typeof value === "string" && value.trim() ? value : null;
-const markdown = (value?: string | null): Markdown | null =>
- text(value) ? { format: "markdown", text: value! } : null;
-
/** Project the saved screener copy, never evaluation-provider content or generated HTML. */
export function projectNextSteps(
results: ScreenerResult,
field?: NextStepsField,
): CrmNextSteps | undefined {
if (!field) return;
- const benefits = Object.entries(results);
- if (
- field.showWhen === "whenComplete" &&
- benefits.some(([, benefit]) => !["TRUE", "FALSE"].includes(benefit.result))
- )
- return {};
+ if (!showsDecided(field, Object.values(results))) return {};
return Object.fromEntries(
- benefits.flatMap(([id, benefit]) => {
- if (!["TRUE", "FALSE"].includes(benefit.result)) return [];
- const content = field.benefitContent?.[id];
- const eligible = benefit.result === "TRUE";
- return [
- [
- id,
- {
- status: eligible ? "eligible" : "ineligible",
- applyUrl: eligible
- ? (webLink(content?.eligible?.applyUrl) ?? null)
- : null,
- help: {
- url: eligible
- ? (webLink(content?.eligible?.helpUrl) ?? null)
- : null,
- phone: eligible
- ? (text(content?.eligible?.helpPhone)?.trim() ?? null)
- : null,
- },
- body: eligible ? markdown(content?.eligible?.body) : null,
- unmetRequirements: eligible
- ? []
- : Object.values(benefit.check_results ?? {})
- .filter((check) => check.result === "FALSE")
- .map((check) => check.aliasName?.trim() || check.name)
- // An unnamed check has nothing to show the host.
- .filter((name): name is string => !!name?.trim()),
- note: eligible ? null : markdown(content?.ineligible?.note),
- },
- ],
- ];
+ Object.entries(results).flatMap(([id, benefit]) => {
+ const steps = benefitNextSteps(benefit, field.benefitContent?.[id]);
+ return steps ? [[id, steps]] : [];
}),
);
}
From 2f5021661b3cb1daefc7d51124f0ed06c4eeabcd Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:10:05 -0400
Subject: [PATCH 06/12] Choose the visible Next steps component from its
conditions
Print and the CRM export found the visible component through fields
that had mounted, so an export read before form-js repainted saw the
previous answers, and Screener had to read it before setting results.
They now evaluate hide conditions the way form-js does, including
groups and repeated items.
Co-Authored-By: Claude Opus 5.5
---
.../components/screener/FormRenderer.test.tsx | 117 +++++++++++++++++-
.../src/components/screener/FormRenderer.tsx | 15 +--
.../src/components/screener/Screener.tsx | 8 +-
.../formJsExtensions/nextSteps/selection.ts | 71 +++++++++--
.../printSummary/PrintSummary.ts | 5 +-
.../screeningResults/screeningResults.ts | 4 -
6 files changed, 190 insertions(+), 30 deletions(-)
diff --git a/builder-frontend/src/components/screener/FormRenderer.test.tsx b/builder-frontend/src/components/screener/FormRenderer.test.tsx
index a01cc098..d3b41577 100644
--- a/builder-frontend/src/components/screener/FormRenderer.test.tsx
+++ b/builder-frontend/src/components/screener/FormRenderer.test.tsx
@@ -1,4 +1,5 @@
// @vitest-environment jsdom
+import { createSignal } from "solid-js";
import { render } from "solid-js/web";
import { afterEach, describe, expect, it, vi } from "vitest";
import FormRenderer from "./FormRenderer";
@@ -75,12 +76,126 @@ describe("FormRenderer host prefill", () => {
container
.querySelector('input[type="checkbox"]')!
.click();
- await vi.waitFor(() => expect(provider(results)).toBeUndefined());
+ // Follows the answers at once, without waiting for form-js to repaint.
+ expect(provider(results)).toBeUndefined();
dispose();
dispose = undefined;
expect(register).toHaveBeenLastCalledWith(undefined);
});
+ it("reads visibility from conditions, including groups, while the form re-imports", async () => {
+ const register = vi.fn();
+ const [hidden, setHidden] = createSignal([]);
+ const content = (body: string) => ({
+ benefit: { eligible: { body } },
+ });
+ dispose = render(
+ () => (
+ ({})}
+ hiddenQuestionPaths={hidden}
+ submitForm={() => {}}
+ registerNextStepsProvider={register}
+ />
+ ),
+ document.body.appendChild(document.createElement("div")),
+ );
+ await vi.waitFor(() => expect(register).toHaveBeenCalledOnce());
+ const results = {
+ benefit: { name: "Benefit", result: "TRUE" as const, check_results: {} },
+ };
+ const provider = register.mock.calls[0][0];
+ expect(provider(results).benefit.body.text).toBe("Shown group");
+ // Hiding a question re-imports the form; the export must not see a gap.
+ setHidden(["city"]);
+ expect(provider(results).benefit.body.text).toBe("Shown group");
+ });
+
+ it.each([
+ [[{ show: false }, { show: true }], "Per item"],
+ [[{ show: false }], undefined],
+ ])(
+ "checks Next steps in a repeated group against each item (%j)",
+ async (people, body) => {
+ const register = vi.fn();
+ dispose = render(
+ () => (
+ ({ people })}
+ hiddenQuestionPaths={() => []}
+ submitForm={() => {}}
+ registerNextStepsProvider={register}
+ />
+ ),
+ document.body.appendChild(document.createElement("div")),
+ );
+ await vi.waitFor(() => expect(register).toHaveBeenCalledOnce());
+ const exported = register.mock.calls[0][0]({
+ benefit: { name: "Benefit", result: "TRUE", check_results: {} },
+ });
+ expect(exported?.benefit.body?.text).toBe(body);
+ },
+ );
+
it("evaluates unknown host answers as null until the user answers them", async () => {
const submitForm = vi.fn();
const container = document.body.appendChild(document.createElement("div"));
diff --git a/builder-frontend/src/components/screener/FormRenderer.tsx b/builder-frontend/src/components/screener/FormRenderer.tsx
index 6554ad63..c77f83cc 100644
--- a/builder-frontend/src/components/screener/FormRenderer.tsx
+++ b/builder-frontend/src/components/screener/FormRenderer.tsx
@@ -16,7 +16,6 @@ import {
projectNextSteps,
type NextStepsProvider,
} from "@/integrations/nextSteps";
-import type { ScreeningResultsService } from "../screenerEditor/formJsExtensions/screeningResults/screeningResults";
import type { ScreenerResult } from "@/types";
import { hideQuestions } from "@/utils/questionVotes";
import { normalizeArrayFieldData } from "@/utils/arrayFieldData";
@@ -108,16 +107,12 @@ function FormRenderer({
.importSchema(hideQuestions(schema, hiddenQuestionPaths()), formData())
.then(() => {
if (disposed) return;
- registerNextStepsProvider?.((results) => {
- const service =
- form!.get("screeningResults");
- const fields =
- (form!.get("formFieldRegistry") as any).getForm()?.components ?? [];
- return projectNextSteps(
+ registerNextStepsProvider?.((results) =>
+ projectNextSteps(
results,
- firstVisibleNextSteps(fields, service.isNextStepsFieldShown),
- );
- });
+ firstVisibleNextSteps((name) => form!.get(name)),
+ ),
+ );
currentData = cloneDeep(form?._getState().data || formData());
if (evaluateInitialData) {
unknownPaths = findFilledUnknownPaths(formData(), currentData);
diff --git a/builder-frontend/src/components/screener/Screener.tsx b/builder-frontend/src/components/screener/Screener.tsx
index 9c6fa0c4..6af99f92 100644
--- a/builder-frontend/src/components/screener/Screener.tsx
+++ b/builder-frontend/src/components/screener/Screener.tsx
@@ -102,12 +102,14 @@ export default function Screener() {
data,
);
if (sequence !== evaluationSequence) return;
- // Read visible content before setting results can re-import the form to hide questions.
- const nextSteps = nextStepsProvider?.(evaluationResult);
setScreenerResult(evaluationResult);
setResultsStale(false);
setEvaluationFailed(false);
- bridge?.result(data, evaluationResult, nextSteps);
+ bridge?.result(
+ data,
+ evaluationResult,
+ nextStepsProvider?.(evaluationResult),
+ );
} catch (err) {
if (sequence !== evaluationSequence) return;
setEvaluationFailed(true);
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
index 5579de5c..953c75e4 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
@@ -1,14 +1,69 @@
+import get from "lodash/get";
+import { buildExpressionContext } from "@bpmn-io/form-js-viewer";
import type { NextStepsField } from "./NextSteps";
import { NEXT_STEPS_TYPE } from "./content";
-/** Shared by print and CRM exports: use the first rendered component in schema order. */
+type ExpressionContext = { data: any; this: any; parent: any; i: number[] };
+
+/**
+ * Shared by print and CRM exports: the first component in schema order that form-js shows,
+ * judged by its and its groups' hide conditions against the current answers, as form-js
+ * judges them. Reading conditions rather than mounted fields keeps a re-import from
+ * briefly hiding every Next steps component.
+ */
export function firstVisibleNextSteps(
- fields: any[],
- isShown: (id: string) => boolean,
+ getService: (name: string) => any,
): NextStepsField | undefined {
- for (const field of fields) {
- if (field.type === NEXT_STEPS_TYPE && isShown(field.id)) return field;
- const nested = firstVisibleNextSteps(field.components ?? [], isShown);
- if (nested) return nested;
- }
+ const form = getService("formFieldRegistry").getForm();
+ if (!form) return;
+ const conditionChecker = getService("conditionChecker");
+ const pathRegistry = getService("pathRegistry");
+ const formFields = getService("formFields");
+ const { data, initialData } = getService("form")._getState();
+ // The root context form-js renders with: answers minus those hidden by conditions.
+ const filtered = {
+ ...initialData,
+ ...conditionChecker.applyConditions(data, data),
+ };
+ const find = (
+ fields: any[] | undefined,
+ context: ExpressionContext,
+ indexes: Record,
+ ): NextStepsField | undefined => {
+ for (const field of fields ?? []) {
+ const hide = field.conditional?.hide;
+ if (
+ hide &&
+ conditionChecker.check(hide, buildExpressionContext(context)) === true
+ )
+ continue;
+ if (field.type === NEXT_STEPS_TYPE) return field;
+ if (!formFields.get(field.type)?.config.repeatable) {
+ const nested = find(field.components, context, indexes);
+ if (nested) return nested;
+ continue;
+ }
+ // A repeated group renders its components once per item, each in its own scope.
+ const items = get(data, pathRegistry.getValuePath(field, { indexes }));
+ const rows: unknown[] = Array.isArray(items) ? items : [];
+ for (const [index, item] of rows.entries()) {
+ const nested = find(
+ field.components,
+ {
+ data: context.data,
+ this: item,
+ parent: buildExpressionContext({ ...context, data: context.this }),
+ i: [...context.i, index + 1],
+ },
+ { ...indexes, [field.id]: index },
+ );
+ if (nested) return nested;
+ }
+ }
+ };
+ return find(
+ form.components,
+ { data: filtered, this: filtered, parent: null, i: [] },
+ {},
+ );
}
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
index a70e15d5..2a7bc7d9 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.ts
@@ -76,10 +76,7 @@ export function PrintSummary() {
setError("");
// Print what the person sees: skip Next steps hidden by a condition.
const source: NextStepsField =
- firstVisibleNextSteps(
- context.getService("formFieldRegistry").getForm()?.components ?? [],
- service.isNextStepsFieldShown,
- ) ?? {};
+ firstVisibleNextSteps(context.getService) ?? {};
const root = document.createElement("article");
root.className = "bdt-print-root";
const printMedia = window.matchMedia?.("print");
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts
index 6a682a49..bc35b2f6 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/screeningResults/screeningResults.ts
@@ -68,10 +68,6 @@ export class ScreeningResultsService {
isNextStepsShown = (): boolean => this.reportedNextStepsShown;
- /** Whether this Next steps field is rendered, so not hidden by a condition. */
- isNextStepsFieldShown = (fieldId: string): boolean =>
- this.nextStepsShown.includes(fieldId);
-
private reportNextStepsShown(): void {
const shown = this.nextStepsShown.length > 0;
if (shown === this.reportedNextStepsShown) return;
From 9260409d6a420bc07319f0dd4d6ef98c83f7eb44 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:11:12 -0400
Subject: [PATCH 07/12] Skip the next steps projection when no CRM host is
connected
Standalone screeners projected every evaluation and threw it away.
Co-Authored-By: Claude Opus 5.5
---
.../src/components/screener/Screener.test.tsx | 4 ++++
builder-frontend/src/components/screener/Screener.tsx | 10 +++++++---
2 files changed, 11 insertions(+), 3 deletions(-)
diff --git a/builder-frontend/src/components/screener/Screener.test.tsx b/builder-frontend/src/components/screener/Screener.test.tsx
index a7f8db4c..f20adaa2 100644
--- a/builder-frontend/src/components/screener/Screener.test.tsx
+++ b/builder-frontend/src/components/screener/Screener.test.tsx
@@ -21,6 +21,7 @@ const integration = vi.hoisted(() => ({
error: vi.fn(),
fail: vi.fn(),
origin: "https://crm.example",
+ registerNextStepsProvider: undefined as unknown,
}));
vi.mock("@solidjs/router", () => ({
@@ -49,6 +50,7 @@ vi.mock("@/integrations/screenerBridge", () => ({
}));
vi.mock("./FormRenderer", () => ({
default: (props: any) => {
+ integration.registerNextStepsProvider = props.registerNextStepsProvider;
onMount(() => {
if (props.evaluateInitialData) props.submitForm(props.formData());
});
@@ -114,6 +116,7 @@ describe("published screener integration lifecycle", () => {
initialData,
),
);
+ expect(integration.registerNextStepsProvider).toBeTypeOf("function");
container.querySelector("button")!.click();
await vi.waitFor(() => expect(integration.result).toHaveBeenCalledOnce());
expect(integration.result).toHaveBeenLastCalledWith(
@@ -261,5 +264,6 @@ describe("published screener integration lifecycle", () => {
container.querySelector("button")!.click();
await vi.waitFor(() => expect(container.textContent).toContain("Eligible"));
expect(integration.result).not.toHaveBeenCalled();
+ expect(integration.registerNextStepsProvider).toBeUndefined();
});
});
diff --git a/builder-frontend/src/components/screener/Screener.tsx b/builder-frontend/src/components/screener/Screener.tsx
index 6af99f92..0b386788 100644
--- a/builder-frontend/src/components/screener/Screener.tsx
+++ b/builder-frontend/src/components/screener/Screener.tsx
@@ -150,9 +150,13 @@ export default function Screener() {
{
- nextStepsProvider = provider;
- }}
+ // Only a CRM host receives next steps; standalone screeners skip the projection.
+ registerNextStepsProvider={
+ bridge &&
+ ((provider) => {
+ nextStepsProvider = provider;
+ })
+ }
screenerName={() => screener()?.screenerName ?? ""}
schema={screener()?.formSchema || {}}
formData={formData}
From d22d067e7a8438c3e7b2bcfa4fc919e4207fc5a3 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:11:36 -0400
Subject: [PATCH 08/12] Render the Salesforce unmet-requirements list only when
it has items
Eligible benefits got an empty list that screen readers announced.
Co-Authored-By: Claude Opus 5.5
---
.../bdtScreeningResults/bdtScreeningResults.html | 12 +++++++-----
.../salesforce/bdtScreeningResults/formatResults.js | 1 +
examples/crm/salesforce/tests/formatResults.test.mjs | 2 ++
3 files changed, 10 insertions(+), 5 deletions(-)
diff --git a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html
index d0fef037..29a01759 100644
--- a/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html
+++ b/examples/crm/salesforce/bdtScreeningResults/bdtScreeningResults.html
@@ -55,11 +55,13 @@ Next steps
value={benefit.body}
>
-
-
- - {requirement.name}
-
-
+
+
+
+ - {requirement.name}
+
+
+
0,
applyUrl,
helpUrl,
phone,
diff --git a/examples/crm/salesforce/tests/formatResults.test.mjs b/examples/crm/salesforce/tests/formatResults.test.mjs
index 59fd9e5c..557180b0 100644
--- a/examples/crm/salesforce/tests/formatResults.test.mjs
+++ b/examples/crm/salesforce/tests/formatResults.test.mjs
@@ -40,9 +40,11 @@ test("formats saved contacts, instructions and requirements while excluding unde
assert.equal(view.benefits[0].applyUrl, "https://example.org/apply");
assert.equal(view.benefits[0].body, "Bring **ID**.");
assert.equal(view.benefits[0].phone, "215-555-0100");
+ assert.equal(view.benefits[0].hasUnmetRequirements, false);
assert.deepEqual(view.benefits[1].unmetRequirements, [
{ id: "0", name: "Income limit" },
]);
+ assert.equal(view.benefits[1].hasUnmetRequirements, true);
assert.equal(view.benefits[1].note, "Ask about other help.");
assert.equal(view.benefits[2].hasNextSteps, undefined);
});
From 49698e7dbe905cc0b01c8b8049a63f9e71e65fe1 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:11:55 -0400
Subject: [PATCH 09/12] Leave out empty saved next steps in the browser demo
A benefit with no usable copy showed an empty labeled region, and an
empty list when ineligible, unlike the Salesforce example.
Co-Authored-By: Claude Opus 5.5
---
examples/crm/browser/demo.js | 21 +++++++++++----------
1 file changed, 11 insertions(+), 10 deletions(-)
diff --git a/examples/crm/browser/demo.js b/examples/crm/browser/demo.js
index 0cb6d09a..da1bc5b8 100644
--- a/examples/crm/browser/demo.js
+++ b/examples/crm/browser/demo.js
@@ -122,19 +122,20 @@ function appendNextSteps(item, steps, outcome) {
paragraph(`Help phone: ${steps.help.phone}`);
if (steps.body?.format === "markdown") paragraph(steps.body.text);
} else {
- if (Array.isArray(steps.unmetRequirements)) {
- const list = document.createElement("ul");
- for (const requirement of steps.unmetRequirements) {
- if (typeof requirement !== "string") continue;
- const li = document.createElement("li");
- li.textContent = requirement;
- list.append(li);
- }
- section.append(list);
+ const list = document.createElement("ul");
+ for (const requirement of Array.isArray(steps.unmetRequirements)
+ ? steps.unmetRequirements
+ : []) {
+ if (typeof requirement !== "string") continue;
+ const li = document.createElement("li");
+ li.textContent = requirement;
+ list.append(li);
}
+ if (list.childElementCount) section.append(list);
if (steps.note?.format === "markdown") paragraph(steps.note.text);
}
- item.append(section);
+ // Leave out a benefit with no usable saved content, rather than an empty region.
+ if (section.childElementCount) item.append(section);
}
function renderRecord() {
From a4ae3fda8bd82c38c3964b6397e338e144c9f153 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:15:45 -0400
Subject: [PATCH 10/12] Run the CRM example tests in the test runner and CI
The example tests, including the new Salesforce URL and outcome
checks, ran only by hand, so regressions passed devbox run test.
Co-Authored-By: Claude Opus 5.5
---
.github/workflows/run-tests.yml | 4 ++--
AGENTS.md | 2 +-
bin/run-all-tests | 20 +++++++++++++++++---
3 files changed, 20 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml
index 2f858ce9..6ef7423e 100644
--- a/.github/workflows/run-tests.yml
+++ b/.github/workflows/run-tests.yml
@@ -16,7 +16,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- suite: [builder-frontend, builder-api, library-api, e2e]
+ suite: [builder-frontend, builder-api, library-api, examples, e2e]
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -25,7 +25,7 @@ jobs:
uses: ./.github/actions/devbox-setup
- name: Cache Maven dependencies
- if: matrix.suite != 'builder-frontend'
+ if: matrix.suite != 'builder-frontend' && matrix.suite != 'examples'
uses: actions/cache@v4
with:
path: ~/.m2/repository
diff --git a/AGENTS.md b/AGENTS.md
index 80b9ba7a..15b9c1a2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -15,7 +15,7 @@ This is a monorepo for building and publishing benefit eligibility screeners. Ke
- Preferred one-time setup: `bin/install-devbox && devbox run setup`
- In worktrees, agents may create the ignored root `.env` from `.env.example` when needed to run Devbox commands. The preferred setup command above does this automatically.
- Start the development stack: `devbox services up`
-- All tests: `devbox run test` (wrapper: `bin/run-all-tests`; accepts `--fail-fast` and suite names `builder-frontend`, `builder-api`, `library-api`, `e2e`)
+- All tests: `devbox run test` (wrapper: `bin/run-all-tests`; accepts `--fail-fast` and suite names `builder-frontend`, `builder-api`, `library-api`, `examples`, `e2e`)
- Backend tests: `(cd builder-api && mvn test)`
- Library tests: `(cd library-api && mvn test)`; DMN API tests require a running library service, then `(cd library-api/test/bdt && bru run)`
- Frontend tests: `(cd builder-frontend && npm test)`; frontend build: `(cd builder-frontend && npm run build)`
diff --git a/bin/run-all-tests b/bin/run-all-tests
index 7ceb053a..91d4e7b3 100755
--- a/bin/run-all-tests
+++ b/bin/run-all-tests
@@ -6,11 +6,12 @@
# 1. builder-frontend - Vitest unit tests (npm test)
# 2. builder-api - JVM unit/integration tests (mvn test)
# 3. library-api - JVM unit/integration tests (mvn test)
-# 4. e2e - bin/run-e2e-tests, which boots the full dev stack with
+# 4. examples - Node tests for the CRM examples (node --test)
+# 5. e2e - bin/run-e2e-tests, which boots the full dev stack with
# devbox services and then runs the library-api Bruno
# collection followed by the Playwright suite.
#
-# The unit suites run first because they need nothing but npm and Maven, while
+# The unit suites run first because they need nothing but Node and Maven, while
# the e2e suite takes exclusive ownership of the local service ports and swaps
# the root emulator-data directory for the e2e fixtures.
#
@@ -27,7 +28,7 @@ source "$SCRIPT_DIR/functions"
cd "$PROJECT_ROOT"
-ALL_SUITES=(builder-frontend builder-api library-api e2e)
+ALL_SUITES=(builder-frontend builder-api library-api examples e2e)
FAIL_FAST=0
usage() {
@@ -42,6 +43,7 @@ Suites:
builder-frontend builder-frontend Vitest tests (npm test)
builder-api builder-api JVM tests (mvn test)
library-api library-api JVM tests (mvn test)
+ examples CRM example Node tests (node --test)
e2e full dev stack, library-api Bruno collection, Playwright suite
With no suite arguments, all suites run in the order listed above.
@@ -154,6 +156,10 @@ if suite_selected builder-api || suite_selected library-api; then
require_command mvn
fi
+if suite_selected examples; then
+ require_command node
+fi
+
# The JVM suites read component .env files directly, and bin/run-e2e-tests needs
# the root .env for the Devbox service graph. Create any that are missing from
# the checked-in examples before the first suite runs.
@@ -195,6 +201,10 @@ run_library_api_suite() {
)
}
+run_examples_suite() {
+ node --test examples/crm/*/tests/*.test.mjs
+}
+
run_e2e_suite() {
bin/run-e2e-tests
}
@@ -266,6 +276,10 @@ if suite_selected library-api; then
run_suite "library-api" run_library_api_suite
fi
+if suite_selected examples; then
+ run_suite "examples" run_examples_suite
+fi
+
if suite_selected e2e; then
run_suite "e2e" run_e2e_suite
fi
From c691bb9a23500ed0570022b580d2b06c2564f034 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 17:15:54 -0400
Subject: [PATCH 11/12] Validate saved next-steps links with one adapter helper
Both example hosts hand-wrote a looser HTTP(S) check than the
screener's. host.js now exports safeHttpUrl, which both hosts use,
and a test keeps it in step with normalizeHttpUrl.
Co-Authored-By: Claude Opus 5.5
---
builder-frontend/public/integrations/host.js | 24 ++++++++++++++
.../src/integrations/screenerBridge.test.ts | 17 +++++++++-
docs/src/content/docs/dev/crm-integrations.md | 2 +-
examples/crm/browser/README.md | 5 +--
examples/crm/browser/demo.js | 32 +++++++------------
examples/crm/salesforce/README.md | 5 +--
.../bdtScreeningResults/formatResults.js | 19 +++--------
.../salesforce/tests/formatResults.test.mjs | 21 ++++++++++--
8 files changed, 80 insertions(+), 45 deletions(-)
diff --git a/builder-frontend/public/integrations/host.js b/builder-frontend/public/integrations/host.js
index fcb889af..4c12aaa7 100644
--- a/builder-frontend/public/integrations/host.js
+++ b/builder-frontend/public/integrations/host.js
@@ -6,6 +6,30 @@ function randomId() {
).join("");
}
+/**
+ * Returns a saved next-steps link if it's one the screener would send: HTTP(S)
+ * with a hostname (no underscores) and no credentials. Otherwise returns null.
+ * Validate saved snapshots with this before making a link clickable.
+ * @param {unknown} value
+ * @returns {string | null}
+ */
+export function safeHttpUrl(value) {
+ if (typeof value !== "string") return null;
+ let url;
+ try {
+ url = new URL(value);
+ } catch {
+ return null;
+ }
+ return ["http:", "https:"].includes(url.protocol) &&
+ url.hostname &&
+ !url.hostname.includes("_") &&
+ !url.username &&
+ !url.password
+ ? url.href
+ : null;
+}
+
/**
* BDT CRM host adapter. Install the listener before navigating the iframe/popup.
* Copy this module into your CRM's source tree if remote modules are restricted.
diff --git a/builder-frontend/src/integrations/screenerBridge.test.ts b/builder-frontend/src/integrations/screenerBridge.test.ts
index 2c65a279..0519930d 100644
--- a/builder-frontend/src/integrations/screenerBridge.test.ts
+++ b/builder-frontend/src/integrations/screenerBridge.test.ts
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CONNECT_TIMEOUT_MS, createScreeningBridge } from "./screenerBridge";
-import { createCrmIntegration } from "../../public/integrations/host.js";
+import {
+ createCrmIntegration,
+ safeHttpUrl,
+} from "../../public/integrations/host.js";
+import { normalizeHttpUrl } from "@/utils/httpUrl";
const results = {
benefit: { name: "Benefit", result: "TRUE" as const, check_results: {} },
@@ -79,6 +83,17 @@ afterEach(() => {
});
describe("published screener CRM bridge", () => {
+ it.each([
+ "https://example.org/apply",
+ "http://example.org/a b",
+ "javascript:alert(1)",
+ "https://user:secret@example.org/",
+ "http://under_score/",
+ "file:///etc/passwd",
+ "not a url",
+ ])("checks saved links as the screener does (%s)", (value) => {
+ expect(safeHttpUrl(value) !== null).toBe(normalizeHttpUrl(value) !== null);
+ });
it.each([false, true])(
"round-trips optional next steps without changing protocol version (JSON=%s)",
(serializeMessages) => {
diff --git a/docs/src/content/docs/dev/crm-integrations.md b/docs/src/content/docs/dev/crm-integrations.md
index 1a83e718..35026fa8 100644
--- a/docs/src/content/docs/dev/crm-integrations.md
+++ b/docs/src/content/docs/dev/crm-integrations.md
@@ -228,7 +228,7 @@ The payload contains structured data, never rendered HTML. Treat Markdown as
untrusted content: display it as plain text (as the examples do), or use a
sanitizing Markdown renderer. Validate links before making them clickable. The
screener emits only HTTP(S) application/help URLs, but hosts must still validate
-any saved snapshot they read. Save `nextSteps` alongside `results` only when the
+any saved snapshot they read; `host.js` exports `safeHttpUrl` for this. Save `nextSteps` alongside `results` only when the
user chooses to save; the protocol does not change persistence authorization.
The screener repeats `ready` about every 500 ms until it's initialized, so a
diff --git a/examples/crm/browser/README.md b/examples/crm/browser/README.md
index 74592720..4c7463da 100644
--- a/examples/crm/browser/README.md
+++ b/examples/crm/browser/README.md
@@ -87,8 +87,9 @@ Firebase emulators, login, published screener, or CRM account.
New result messages may include `nextSteps` alongside `results`. The example
saves both on the user's explicit Save action and shows application/help links,
contact numbers, instructions, and unmet requirements from that snapshot.
-Markdown is displayed as plain text rather than inserted as HTML. Links accept
-only HTTP(S) destinations without embedded credentials. Older saved records
+Markdown is displayed as plain text rather than inserted as HTML. Links pass
+through the adapter's `safeHttpUrl`, which accepts only the HTTP(S) links the
+screener sends. Older saved records
without `nextSteps` continue to display their benefit decisions.
Only visible screener content is sent. A missing `nextSteps` field or `{}` in a
diff --git a/examples/crm/browser/demo.js b/examples/crm/browser/demo.js
index da1bc5b8..cd6148bd 100644
--- a/examples/crm/browser/demo.js
+++ b/examples/crm/browser/demo.js
@@ -1,4 +1,4 @@
-import { createCrmIntegration } from "./host.js";
+import { createCrmIntegration, safeHttpUrl } from "./host.js";
import { clientToScreenerData } from "./clientMapping.mjs";
const element = (id) => document.getElementById(id);
@@ -94,26 +94,16 @@ function appendNextSteps(item, steps, outcome) {
section.append(p);
};
const link = (value, label) => {
- if (typeof value !== "string") return;
- try {
- const url = new URL(value);
- if (
- !["http:", "https:"].includes(url.protocol) ||
- url.username ||
- url.password
- )
- return;
- const a = document.createElement("a");
- a.href = url.href;
- a.textContent = label;
- a.target = "_blank";
- a.rel = "noopener noreferrer";
- const p = document.createElement("p");
- p.append(a);
- section.append(p);
- } catch {
- /* Ignore invalid saved URLs. */
- }
+ const href = safeHttpUrl(value);
+ if (!href) return;
+ const a = document.createElement("a");
+ a.href = href;
+ a.textContent = label;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer";
+ const p = document.createElement("p");
+ p.append(a);
+ section.append(p);
};
if (outcome === "eligible") {
link(steps.applyUrl, "Apply for this benefit");
diff --git a/examples/crm/salesforce/README.md b/examples/crm/salesforce/README.md
index fcb235f4..8ddf9994 100644
--- a/examples/crm/salesforce/README.md
+++ b/examples/crm/salesforce/README.md
@@ -126,8 +126,9 @@ Salesforce references:
New result messages may include `nextSteps` alongside `results`. The example
saves both on the user's explicit Save action and shows application/help links,
contact numbers, instructions, and unmet requirements from that snapshot.
-Markdown is displayed as plain text rather than inserted as HTML. Links accept
-only HTTP(S) destinations without embedded credentials. Older saved records
+Markdown is displayed as plain text rather than inserted as HTML. Links pass
+through the adapter's `safeHttpUrl`, which accepts only the HTTP(S) links the
+screener sends. Older saved records
without `nextSteps` continue to display their benefit decisions. If the
snapshot with `nextSteps` exceeds the field size, the example saves the
decisions without `nextSteps` and says so.
diff --git a/examples/crm/salesforce/bdtScreeningResults/formatResults.js b/examples/crm/salesforce/bdtScreeningResults/formatResults.js
index 5d98ecb4..2705a869 100644
--- a/examples/crm/salesforce/bdtScreeningResults/formatResults.js
+++ b/examples/crm/salesforce/bdtScreeningResults/formatResults.js
@@ -1,3 +1,5 @@
+import { safeHttpUrl } from "c/bdtCrmHost";
+
const isObject = (value) =>
value !== null && typeof value === "object" && !Array.isArray(value);
@@ -28,19 +30,6 @@ function checkName(check) {
.trim();
}
-function safeUrl(value) {
- if (typeof value !== "string") return null;
- try {
- const url = new URL(value);
- return ["http:", "https:"].includes(url.protocol) &&
- !url.username &&
- !url.password
- ? url.href
- : null;
- } catch {
- return null;
- }
-}
function markdownText(value) {
return isObject(value) &&
value.format === "markdown" &&
@@ -56,8 +45,8 @@ function nextStepsView(steps, result) {
)
return {};
const eligible = result === "TRUE";
- const applyUrl = eligible ? safeUrl(steps.applyUrl) : null;
- const helpUrl = eligible ? safeUrl(steps.help?.url) : null;
+ const applyUrl = eligible ? safeHttpUrl(steps.applyUrl) : null;
+ const helpUrl = eligible ? safeHttpUrl(steps.help?.url) : null;
const phone =
eligible && typeof steps.help?.phone === "string" ? steps.help.phone : "";
const body = eligible ? markdownText(steps.body) : "";
diff --git a/examples/crm/salesforce/tests/formatResults.test.mjs b/examples/crm/salesforce/tests/formatResults.test.mjs
index 557180b0..2667c19f 100644
--- a/examples/crm/salesforce/tests/formatResults.test.mjs
+++ b/examples/crm/salesforce/tests/formatResults.test.mjs
@@ -2,9 +2,20 @@ import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
-const source = await readFile(
- new URL("../bdtScreeningResults/formatResults.js", import.meta.url),
- "utf8",
+// In Salesforce, c/bdtCrmHost is the copied host adapter.
+const source = (
+ await readFile(
+ new URL("../bdtScreeningResults/formatResults.js", import.meta.url),
+ "utf8",
+ )
+).replace(
+ '"c/bdtCrmHost"',
+ JSON.stringify(
+ new URL(
+ "../../../../builder-frontend/public/integrations/host.js",
+ import.meta.url,
+ ).href,
+ ),
);
const { formatSavedResults } = await import(
`data:text/javascript;base64,${Buffer.from(source).toString("base64")}`
@@ -58,9 +69,13 @@ test("reads older snapshots and drops unsafe links without interpreting Markdown
const unsafe = structuredClone(snapshot);
unsafe.nextSteps.housing.applyUrl = "javascript:alert(1)";
unsafe.nextSteps.housing.help.url = "https://user:secret@example.org/";
+ unsafe.nextSteps.food.status = "eligible";
+ unsafe.results.food.result = "TRUE";
+ unsafe.nextSteps.food.applyUrl = "http://under_score/";
unsafe.nextSteps.housing.body.text = "";
const view = formatSavedResults(JSON.stringify(unsafe));
assert.equal(view.benefits[0].applyUrl, null);
assert.equal(view.benefits[0].helpUrl, null);
+ assert.equal(view.benefits[1].applyUrl, null);
assert.equal(view.benefits[0].body, "");
});
From d3d426ee5768dd5980e2f0dc9788e709ecd89392 Mon Sep 17 00:00:00 2001
From: Preston Cabe
Date: Tue, 27 Oct 2026 18:07:20 -0400
Subject: [PATCH 12/12] Respect disabled repetition when selecting next steps
---
.../components/screener/FormRenderer.test.tsx | 52 +++++++++++++++++++
.../formJsExtensions/nextSteps/selection.ts | 5 +-
2 files changed, 56 insertions(+), 1 deletion(-)
diff --git a/builder-frontend/src/components/screener/FormRenderer.test.tsx b/builder-frontend/src/components/screener/FormRenderer.test.tsx
index d3b41577..4533a1ef 100644
--- a/builder-frontend/src/components/screener/FormRenderer.test.tsx
+++ b/builder-frontend/src/components/screener/FormRenderer.test.tsx
@@ -142,6 +142,58 @@ describe("FormRenderer host prefill", () => {
expect(provider(results).benefit.body.text).toBe("Shown group");
});
+ it("exports visible instructions from a dynamic list with repetition disabled", async () => {
+ const register = vi.fn();
+ const container = document.body.appendChild(document.createElement("div"));
+ dispose = render(
+ () => (
+ ({ person: { show: true } })}
+ hiddenQuestionPaths={() => []}
+ submitForm={() => {}}
+ registerNextStepsProvider={register}
+ />
+ ),
+ container,
+ );
+ await vi.waitFor(() => expect(register).toHaveBeenCalledOnce());
+ const exported = register.mock.calls[0][0]({
+ benefit: { name: "Benefit", result: "TRUE", check_results: {} },
+ });
+ expect(exported.benefit.body.text).toBe("Single-person instructions");
+ });
+
it.each([
[[{ show: false }, { show: true }], "Per item"],
[[{ show: false }], undefined],
diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
index 953c75e4..348769b3 100644
--- a/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
+++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts
@@ -38,7 +38,10 @@ export function firstVisibleNextSteps(
)
continue;
if (field.type === NEXT_STEPS_TYPE) return field;
- if (!formFields.get(field.type)?.config.repeatable) {
+ if (
+ !formFields.get(field.type)?.config.repeatable ||
+ !field.isRepeating
+ ) {
const nested = find(field.components, context, indexes);
if (nested) return nested;
continue;