Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,33 @@ describe("assembleStandaloneHtmlFromActivity", () => {
expect(doc).toContain('document.title = "<\\/script>";');
});

it("keeps js pieces separate when they omit trailing semicolons", async () => {
const doc = assembleStandaloneHtmlFromActivity({
jsFunctions: "let count = 0",
jsExpressions: [
"window.exportFirst = count + 1",
"(function () { window.exportSecond = 2 })()",
"[3].forEach(function (n) { window.exportThird = n })",
],
});
const script = doc.slice(
doc.lastIndexOf("<script>") + "<script>".length,
doc.lastIndexOf("</script>")
);
const globals = window as unknown as Record<string, unknown>;
try {
expect(() => new Function(script)()).not.toThrow();
await Promise.resolve();
expect(globals.exportFirst).toBe(1);
expect(globals.exportSecond).toBe(2);
expect(globals.exportThird).toBe(3);
} finally {
delete globals.exportFirst;
delete globals.exportSecond;
delete globals.exportThird;
}
});

it("neutralizes closing style sequences embedded in generated css", () => {
const doc = assembleStandaloneHtmlFromActivity(
{
Expand Down
11 changes: 9 additions & 2 deletions apps/app/src/components/generative-ui/export-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ export interface StandaloneActivityContent {

const WEBSANDBOX_STUB = `window.Websandbox = { connection: { remote: { sendPrompt: async () => {}, openLink: async ({ url }) => { if (/^https:/.test(url)) window.open(url, "_blank", "noopener,noreferrer"); } } } };`;

// The live sandbox runs jsFunctions and each jsExpression as separate scripts,
// so generated code often omits trailing semicolons. Joined into one script,
// automatic semicolon insertion would merge the pieces: "let n = 0" followed
// by "(function () {...})()" parses as a call on 0. An explicit separator keeps
// each piece a separate statement.
const STATEMENT_SEPARATOR = "\n;\n";

function escapeScriptClose(js: string): string {
return js.replace(/<\/script/gi, "<\\/script");
}
Expand Down Expand Up @@ -56,15 +63,15 @@ export function assembleStandaloneHtmlFromActivity(
...(expressions.length > 0
? [
`(async () => {
${expressions.map(escapeScriptClose).join("\n")}
${expressions.map(escapeScriptClose).join(STATEMENT_SEPARATOR)}
})();`,
]
: []),
];
const generatedScript =
scriptParts.length > 0
? `<script>
${scriptParts.join("\n")}
${scriptParts.join(STATEMENT_SEPARATOR)}
</script>`
: "";
return `<!DOCTYPE html>
Expand Down