@elyracode/web-ui 0.9.58 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/components/SandboxedIframe.d.ts +15 -1
  3. package/dist/components/SandboxedIframe.d.ts.map +1 -1
  4. package/dist/components/SandboxedIframe.js +129 -67
  5. package/dist/components/SandboxedIframe.js.map +1 -1
  6. package/dist/components/sandbox/RuntimeMessageRouter.d.ts +12 -2
  7. package/dist/components/sandbox/RuntimeMessageRouter.d.ts.map +1 -1
  8. package/dist/components/sandbox/RuntimeMessageRouter.js +26 -2
  9. package/dist/components/sandbox/RuntimeMessageRouter.js.map +1 -1
  10. package/package.json +18 -8
  11. package/example/README.md +0 -61
  12. package/example/index.html +0 -13
  13. package/example/package.json +0 -25
  14. package/example/src/app.css +0 -1
  15. package/example/src/css-modules.d.ts +0 -3
  16. package/example/src/custom-messages.ts +0 -99
  17. package/example/src/main.ts +0 -421
  18. package/example/tsconfig.json +0 -23
  19. package/example/vite.config.ts +0 -6
  20. package/scripts/count-prompt-tokens.ts +0 -88
  21. package/src/ChatPanel.ts +0 -209
  22. package/src/app.css +0 -68
  23. package/src/components/AgentInterface.ts +0 -403
  24. package/src/components/AttachmentTile.ts +0 -107
  25. package/src/components/ConsoleBlock.ts +0 -72
  26. package/src/components/CustomProviderCard.ts +0 -100
  27. package/src/components/ExpandableSection.ts +0 -46
  28. package/src/components/Input.ts +0 -113
  29. package/src/components/MessageEditor.ts +0 -405
  30. package/src/components/MessageList.ts +0 -98
  31. package/src/components/Messages.ts +0 -383
  32. package/src/components/ProviderKeyInput.ts +0 -153
  33. package/src/components/SandboxedIframe.ts +0 -627
  34. package/src/components/StreamingMessageContainer.ts +0 -103
  35. package/src/components/ThinkingBlock.ts +0 -43
  36. package/src/components/message-renderer-registry.ts +0 -28
  37. package/src/components/sandbox/ArtifactsRuntimeProvider.ts +0 -226
  38. package/src/components/sandbox/AttachmentsRuntimeProvider.ts +0 -68
  39. package/src/components/sandbox/ConsoleRuntimeProvider.ts +0 -188
  40. package/src/components/sandbox/FileDownloadRuntimeProvider.ts +0 -114
  41. package/src/components/sandbox/RuntimeMessageBridge.ts +0 -82
  42. package/src/components/sandbox/RuntimeMessageRouter.ts +0 -215
  43. package/src/components/sandbox/SandboxRuntimeProvider.ts +0 -54
  44. package/src/components/sandbox/runtime-messages.ts +0 -146
  45. package/src/dialogs/ApiKeyPromptDialog.ts +0 -75
  46. package/src/dialogs/AttachmentOverlay.ts +0 -637
  47. package/src/dialogs/CustomProviderDialog.ts +0 -274
  48. package/src/dialogs/ModelSelector.ts +0 -370
  49. package/src/dialogs/PersistentStorageDialog.ts +0 -144
  50. package/src/dialogs/ProvidersModelsTab.ts +0 -212
  51. package/src/dialogs/SessionListDialog.ts +0 -150
  52. package/src/dialogs/SettingsDialog.ts +0 -218
  53. package/src/index.ts +0 -120
  54. package/src/prompts/prompts.ts +0 -282
  55. package/src/storage/app-storage.ts +0 -60
  56. package/src/storage/backends/indexeddb-storage-backend.ts +0 -193
  57. package/src/storage/store.ts +0 -33
  58. package/src/storage/stores/custom-providers-store.ts +0 -62
  59. package/src/storage/stores/provider-keys-store.ts +0 -33
  60. package/src/storage/stores/sessions-store.ts +0 -136
  61. package/src/storage/stores/settings-store.ts +0 -34
  62. package/src/storage/types.ts +0 -206
  63. package/src/tools/artifacts/ArtifactElement.ts +0 -14
  64. package/src/tools/artifacts/ArtifactPill.ts +0 -26
  65. package/src/tools/artifacts/Console.ts +0 -93
  66. package/src/tools/artifacts/DocxArtifact.ts +0 -213
  67. package/src/tools/artifacts/ExcelArtifact.ts +0 -231
  68. package/src/tools/artifacts/GenericArtifact.ts +0 -117
  69. package/src/tools/artifacts/HtmlArtifact.ts +0 -195
  70. package/src/tools/artifacts/ImageArtifact.ts +0 -116
  71. package/src/tools/artifacts/MarkdownArtifact.ts +0 -82
  72. package/src/tools/artifacts/PdfArtifact.ts +0 -202
  73. package/src/tools/artifacts/SvgArtifact.ts +0 -119
  74. package/src/tools/artifacts/TextArtifact.ts +0 -148
  75. package/src/tools/artifacts/artifacts-tool-renderer.ts +0 -310
  76. package/src/tools/artifacts/artifacts.ts +0 -713
  77. package/src/tools/artifacts/index.ts +0 -7
  78. package/src/tools/extract-document.ts +0 -275
  79. package/src/tools/index.ts +0 -46
  80. package/src/tools/javascript-repl.ts +0 -293
  81. package/src/tools/renderer-registry.ts +0 -130
  82. package/src/tools/renderers/BashRenderer.ts +0 -52
  83. package/src/tools/renderers/CalculateRenderer.ts +0 -58
  84. package/src/tools/renderers/DefaultRenderer.ts +0 -103
  85. package/src/tools/renderers/GetCurrentTimeRenderer.ts +0 -92
  86. package/src/tools/types.ts +0 -15
  87. package/src/utils/attachment-utils.ts +0 -479
  88. package/src/utils/auth-token.ts +0 -22
  89. package/src/utils/format.ts +0 -42
  90. package/src/utils/i18n.ts +0 -653
  91. package/src/utils/model-discovery.ts +0 -290
  92. package/src/utils/proxy-utils.ts +0 -139
  93. package/src/utils/test-sessions.ts +0 -2357
  94. package/tsconfig.build.json +0 -20
  95. package/tsconfig.json +0 -7
@@ -1,627 +0,0 @@
1
- import { LitElement } from "lit";
2
- import { customElement, property } from "lit/decorators.js";
3
- import { ConsoleRuntimeProvider } from "./sandbox/ConsoleRuntimeProvider.js";
4
- import { RuntimeMessageBridge } from "./sandbox/RuntimeMessageBridge.js";
5
- import { type MessageConsumer, RUNTIME_MESSAGE_ROUTER } from "./sandbox/RuntimeMessageRouter.js";
6
- import type { ChromeApi, RuntimeMessage } from "./sandbox/runtime-messages.js";
7
- import type { SandboxRuntimeProvider } from "./sandbox/SandboxRuntimeProvider.js";
8
-
9
- export interface SandboxFile {
10
- fileName: string;
11
- content: string | Uint8Array;
12
- mimeType: string;
13
- }
14
-
15
- export interface SandboxResult {
16
- success: boolean;
17
- console: Array<{ type: string; text: string }>;
18
- files?: SandboxFile[];
19
- error?: { message: string; stack: string };
20
- returnValue?: unknown;
21
- }
22
-
23
- /**
24
- * Function that returns the URL to the sandbox HTML file.
25
- * Used in browser extensions to load sandbox.html via chrome.runtime.getURL().
26
- */
27
- export type SandboxUrlProvider = () => string;
28
-
29
- /**
30
- * Configuration for prepareHtmlDocument
31
- */
32
- export interface PrepareHtmlOptions {
33
- /** True if this is an HTML artifact (inject into existing HTML), false if REPL (wrap in HTML) */
34
- isHtmlArtifact: boolean;
35
- /** True if this is a standalone download (no runtime bridge, no navigation interceptor) */
36
- isStandalone?: boolean;
37
- }
38
-
39
- /**
40
- * Escape HTML special sequences in code to prevent premature tag closure
41
- * @param code Code that will be injected into <script> tags
42
- * @returns Escaped code safe for injection
43
- */
44
- function escapeScriptContent(code: string): string {
45
- return code.replace(/<\/script/gi, "<\\/script");
46
- }
47
-
48
- @customElement("sandbox-iframe")
49
- export class SandboxIframe extends LitElement {
50
- private iframe?: HTMLIFrameElement;
51
-
52
- /**
53
- * Optional: Provide a function that returns the sandbox HTML URL.
54
- * If provided, the iframe will use this URL instead of srcdoc.
55
- * This is required for browser extensions with strict CSP.
56
- */
57
- @property({ attribute: false }) sandboxUrlProvider?: SandboxUrlProvider;
58
-
59
- createRenderRoot() {
60
- return this;
61
- }
62
-
63
- override connectedCallback() {
64
- super.connectedCallback();
65
- }
66
-
67
- override disconnectedCallback() {
68
- super.disconnectedCallback();
69
- // Note: We don't unregister the sandbox here for loadContent() mode
70
- // because the caller (HtmlArtifact) owns the sandbox lifecycle.
71
- // For execute() mode, the sandbox is unregistered in the cleanup function.
72
- this.iframe?.remove();
73
- }
74
-
75
- /**
76
- * Load HTML content into sandbox and keep it displayed (for HTML artifacts)
77
- * @param sandboxId Unique ID
78
- * @param htmlContent Full HTML content
79
- * @param providers Runtime providers to inject
80
- * @param consumers Message consumers to register (optional)
81
- */
82
- public loadContent(
83
- sandboxId: string,
84
- htmlContent: string,
85
- providers: SandboxRuntimeProvider[] = [],
86
- consumers: MessageConsumer[] = [],
87
- ): void {
88
- // Unregister previous sandbox if exists
89
- try {
90
- RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
91
- } catch {
92
- // Sandbox might not exist, that's ok
93
- }
94
-
95
- providers = [new ConsoleRuntimeProvider(), ...providers];
96
-
97
- RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers);
98
-
99
- // loadContent is always used for HTML artifacts (not standalone)
100
- const completeHtml = this.prepareHtmlDocument(sandboxId, htmlContent, providers, {
101
- isHtmlArtifact: true,
102
- isStandalone: false,
103
- });
104
-
105
- // Validate HTML before loading
106
- const validationError = this.validateHtml(completeHtml);
107
- if (validationError) {
108
- console.error("HTML validation failed:", validationError);
109
- // Show error in iframe instead of crashing
110
- this.iframe?.remove();
111
- this.iframe = document.createElement("iframe");
112
- this.iframe.style.cssText = "width: 100%; height: 100%; border: none;";
113
- this.iframe.srcdoc = `
114
- <html>
115
- <body style="font-family: monospace; padding: 20px; background: #fff; color: #000;">
116
- <h3 style="color: #c00;">HTML Validation Error</h3>
117
- <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; overflow-x: auto; white-space: pre-wrap;">${validationError}</pre>
118
- </body>
119
- </html>
120
- `;
121
- this.appendChild(this.iframe);
122
- return;
123
- }
124
-
125
- // Remove previous iframe if exists
126
- this.iframe?.remove();
127
-
128
- if (this.sandboxUrlProvider) {
129
- // Browser extension mode: use sandbox.html with postMessage
130
- this.loadViaSandboxUrl(sandboxId, completeHtml);
131
- } else {
132
- // Web mode: use srcdoc
133
- this.loadViaSrcdoc(sandboxId, completeHtml);
134
- }
135
- }
136
-
137
- private loadViaSandboxUrl(sandboxId: string, completeHtml: string): void {
138
- // Create iframe pointing to sandbox URL
139
- this.iframe = document.createElement("iframe");
140
- this.iframe.sandbox.add("allow-scripts");
141
- this.iframe.sandbox.add("allow-modals");
142
- this.iframe.style.width = "100%";
143
- this.iframe.style.height = "100%";
144
- this.iframe.style.border = "none";
145
- this.iframe.src = this.sandboxUrlProvider!();
146
-
147
- // Update router with iframe reference BEFORE appending to DOM
148
- RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
149
-
150
- // Listen for open-external-url messages from iframe
151
- const externalUrlHandler = (e: MessageEvent) => {
152
- if (e.data.type === "open-external-url" && e.source === this.iframe?.contentWindow) {
153
- // Use chrome.tabs API to open in new tab
154
- const chromeAPI = (globalThis as { chrome?: ChromeApi }).chrome;
155
- if (chromeAPI?.tabs) {
156
- chromeAPI.tabs.create({ url: e.data.url });
157
- } else {
158
- // Fallback for non-extension context
159
- window.open(e.data.url, "_blank");
160
- }
161
- }
162
- };
163
- window.addEventListener("message", externalUrlHandler);
164
-
165
- // Listen for sandbox-ready and sandbox-error messages directly
166
- const readyHandler = (e: MessageEvent) => {
167
- if (e.data.type === "sandbox-ready" && e.source === this.iframe?.contentWindow) {
168
- window.removeEventListener("message", readyHandler);
169
- window.removeEventListener("message", errorHandler);
170
-
171
- // Send content to sandbox
172
- this.iframe?.contentWindow?.postMessage(
173
- {
174
- type: "sandbox-load",
175
- sandboxId,
176
- code: completeHtml,
177
- },
178
- "*",
179
- );
180
- }
181
- };
182
-
183
- const errorHandler = (e: MessageEvent) => {
184
- if (e.data.type === "sandbox-error" && e.source === this.iframe?.contentWindow) {
185
- window.removeEventListener("message", readyHandler);
186
- window.removeEventListener("message", errorHandler);
187
-
188
- // The sandbox.js already sent us the error via postMessage.
189
- // We need to convert it to an execution-error message that the execute() consumer will handle.
190
- // Simulate receiving an execution-error from the sandbox
191
- window.postMessage(
192
- {
193
- sandboxId: sandboxId,
194
- type: "execution-error",
195
- error: { message: e.data.error, stack: e.data.stack },
196
- },
197
- "*",
198
- );
199
- }
200
- };
201
-
202
- window.addEventListener("message", readyHandler);
203
- window.addEventListener("message", errorHandler);
204
-
205
- this.appendChild(this.iframe);
206
- }
207
-
208
- private loadViaSrcdoc(sandboxId: string, completeHtml: string): void {
209
- // Create iframe with srcdoc
210
- this.iframe = document.createElement("iframe");
211
- this.iframe.sandbox.add("allow-scripts");
212
- this.iframe.sandbox.add("allow-modals");
213
- this.iframe.style.width = "100%";
214
- this.iframe.style.height = "100%";
215
- this.iframe.style.border = "none";
216
- this.iframe.srcdoc = completeHtml;
217
-
218
- // Update router with iframe reference BEFORE appending to DOM
219
- RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
220
-
221
- // Listen for open-external-url messages from iframe
222
- const externalUrlHandler = (e: MessageEvent) => {
223
- if (e.data.type === "open-external-url" && e.source === this.iframe?.contentWindow) {
224
- // Fallback for non-extension context
225
- window.open(e.data.url, "_blank");
226
- }
227
- };
228
- window.addEventListener("message", externalUrlHandler);
229
-
230
- this.appendChild(this.iframe);
231
- }
232
-
233
- /**
234
- * Execute code in sandbox
235
- * @param sandboxId Unique ID for this execution
236
- * @param code User code (plain JS for REPL, or full HTML for artifacts)
237
- * @param providers Runtime providers to inject
238
- * @param consumers Additional message consumers (optional, execute has its own internal consumer)
239
- * @param signal Abort signal
240
- * @returns Promise resolving to execution result
241
- */
242
- public async execute(
243
- sandboxId: string,
244
- code: string,
245
- providers: SandboxRuntimeProvider[] = [],
246
- consumers: MessageConsumer[] = [],
247
- signal?: AbortSignal,
248
- isHtmlArtifact: boolean = false,
249
- ): Promise<SandboxResult> {
250
- if (signal?.aborted) {
251
- throw new Error("Execution aborted");
252
- }
253
-
254
- const consoleProvider = new ConsoleRuntimeProvider();
255
- providers = [consoleProvider, ...providers];
256
- RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers);
257
-
258
- // Notify providers that execution is starting
259
- for (const provider of providers) {
260
- provider.onExecutionStart?.(sandboxId, signal);
261
- }
262
-
263
- const files: SandboxFile[] = [];
264
- let completed = false;
265
-
266
- return new Promise((resolve, reject) => {
267
- // 4. Create execution consumer for lifecycle messages
268
- const executionConsumer: MessageConsumer = {
269
- async handleMessage(message: RuntimeMessage): Promise<void> {
270
- if (message.type === "file-returned") {
271
- files.push({
272
- fileName: message.fileName,
273
- content: message.content,
274
- mimeType: message.mimeType,
275
- });
276
- } else if (message.type === "execution-complete") {
277
- completed = true;
278
- cleanup();
279
- resolve({
280
- success: true,
281
- console: consoleProvider.getLogs(),
282
- files,
283
- returnValue: message.returnValue,
284
- });
285
- } else if (message.type === "execution-error") {
286
- completed = true;
287
- cleanup();
288
- resolve({ success: false, console: consoleProvider.getLogs(), error: message.error, files });
289
- }
290
- },
291
- };
292
-
293
- RUNTIME_MESSAGE_ROUTER.addConsumer(sandboxId, executionConsumer);
294
-
295
- const cleanup = () => {
296
- // Notify providers that execution has ended
297
- for (const provider of providers) {
298
- provider.onExecutionEnd?.(sandboxId);
299
- }
300
-
301
- RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId);
302
- signal?.removeEventListener("abort", abortHandler);
303
- clearTimeout(timeoutId);
304
- this.iframe?.remove();
305
- this.iframe = undefined;
306
- };
307
-
308
- // Abort handler
309
- const abortHandler = () => {
310
- if (!completed) {
311
- completed = true;
312
- cleanup();
313
- reject(new Error("Execution aborted"));
314
- }
315
- };
316
-
317
- if (signal) {
318
- signal.addEventListener("abort", abortHandler);
319
- }
320
-
321
- // Timeout handler (30 seconds)
322
- const timeoutId = setTimeout(() => {
323
- if (!completed) {
324
- completed = true;
325
- cleanup();
326
- resolve({
327
- success: false,
328
- console: consoleProvider.getLogs(),
329
- error: { message: "Execution timeout (120s)", stack: "" },
330
- files,
331
- });
332
- }
333
- }, 120000);
334
-
335
- // 4. Prepare HTML and create iframe
336
- const completeHtml = this.prepareHtmlDocument(sandboxId, code, providers, {
337
- isHtmlArtifact,
338
- isStandalone: false,
339
- });
340
-
341
- // 5. Validate HTML before sending to sandbox
342
- const validationError = this.validateHtml(completeHtml);
343
- if (validationError) {
344
- reject(new Error(`HTML validation failed: ${validationError}`));
345
- return;
346
- }
347
-
348
- if (this.sandboxUrlProvider) {
349
- // Browser extension mode: wait for sandbox-ready
350
- this.iframe = document.createElement("iframe");
351
- this.iframe.sandbox.add("allow-scripts", "allow-modals");
352
- this.iframe.style.cssText = "width: 100%; height: 100%; border: none;";
353
- this.iframe.src = this.sandboxUrlProvider();
354
-
355
- // Update router with iframe reference BEFORE appending to DOM
356
- RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
357
-
358
- // Listen for sandbox-ready and sandbox-error messages
359
- const readyHandler = (e: MessageEvent) => {
360
- if (e.data.type === "sandbox-ready" && e.source === this.iframe?.contentWindow) {
361
- window.removeEventListener("message", readyHandler);
362
- window.removeEventListener("message", errorHandler);
363
-
364
- // Send content to sandbox
365
- this.iframe?.contentWindow?.postMessage(
366
- {
367
- type: "sandbox-load",
368
- sandboxId,
369
- code: completeHtml,
370
- },
371
- "*",
372
- );
373
- }
374
- };
375
-
376
- const errorHandler = (e: MessageEvent) => {
377
- if (e.data.type === "sandbox-error" && e.source === this.iframe?.contentWindow) {
378
- window.removeEventListener("message", readyHandler);
379
- window.removeEventListener("message", errorHandler);
380
-
381
- // Convert sandbox-error to execution-error for the execution consumer
382
- window.postMessage(
383
- {
384
- sandboxId: sandboxId,
385
- type: "execution-error",
386
- error: { message: e.data.error, stack: e.data.stack },
387
- },
388
- "*",
389
- );
390
- }
391
- };
392
-
393
- window.addEventListener("message", readyHandler);
394
- window.addEventListener("message", errorHandler);
395
-
396
- this.appendChild(this.iframe);
397
- } else {
398
- // Web mode: use srcdoc
399
- this.iframe = document.createElement("iframe");
400
- this.iframe.sandbox.add("allow-scripts", "allow-modals");
401
- this.iframe.style.cssText = "width: 100%; height: 100%; border: none; display: none;";
402
- this.iframe.srcdoc = completeHtml;
403
-
404
- // Update router with iframe reference BEFORE appending to DOM
405
- RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe);
406
-
407
- this.appendChild(this.iframe);
408
- }
409
- });
410
- }
411
-
412
- /**
413
- * Validate HTML using DOMParser - returns error message if invalid, null if valid
414
- * Note: JavaScript syntax validation is done in sandbox.js to avoid CSP restrictions
415
- */
416
- private validateHtml(html: string): string | null {
417
- try {
418
- const parser = new DOMParser();
419
- const doc = parser.parseFromString(html, "text/html");
420
-
421
- // Check for parser errors
422
- const parserError = doc.querySelector("parsererror");
423
- if (parserError) {
424
- return parserError.textContent || "Unknown parse error";
425
- }
426
-
427
- return null;
428
- } catch (error) {
429
- return error instanceof Error ? error.message : "Unknown validation error";
430
- }
431
- }
432
-
433
- /**
434
- * Prepare complete HTML document with runtime + user code
435
- * PUBLIC so HtmlArtifact can use it for download button
436
- */
437
- public prepareHtmlDocument(
438
- sandboxId: string,
439
- userCode: string,
440
- providers: SandboxRuntimeProvider[] = [],
441
- options?: PrepareHtmlOptions,
442
- ): string {
443
- // Default options
444
- const opts: PrepareHtmlOptions = {
445
- isHtmlArtifact: false,
446
- isStandalone: false,
447
- ...options,
448
- };
449
-
450
- // Runtime script that will be injected
451
- const runtime = this.getRuntimeScript(sandboxId, providers, opts.isStandalone || false);
452
-
453
- // Only check for HTML tags if explicitly marked as HTML artifact
454
- // For javascript_repl, userCode is JavaScript that may contain HTML in string literals
455
- if (opts.isHtmlArtifact) {
456
- // HTML Artifact - inject runtime into existing HTML
457
- const headMatch = userCode.match(/<head[^>]*>/i);
458
- if (headMatch) {
459
- const index = headMatch.index! + headMatch[0].length;
460
- return userCode.slice(0, index) + runtime + userCode.slice(index);
461
- }
462
-
463
- const htmlMatch = userCode.match(/<html[^>]*>/i);
464
- if (htmlMatch) {
465
- const index = htmlMatch.index! + htmlMatch[0].length;
466
- return userCode.slice(0, index) + runtime + userCode.slice(index);
467
- }
468
-
469
- // Fallback: prepend runtime
470
- return runtime + userCode;
471
- } else {
472
- // REPL - wrap code in HTML with runtime and call complete() when done
473
- // Escape </script> in user code to prevent premature tag closure
474
- const escapedUserCode = escapeScriptContent(userCode);
475
-
476
- return `<!DOCTYPE html>
477
- <html>
478
- <head>
479
- ${runtime}
480
- </head>
481
- <body>
482
- <script type="module">
483
- (async () => {
484
- try {
485
- // Wrap user code in async function to capture return value
486
- const userCodeFunc = async () => {
487
- ${escapedUserCode}
488
- };
489
-
490
- const returnValue = await userCodeFunc();
491
-
492
- // Call completion callbacks before complete()
493
- if (window.__completionCallbacks && window.__completionCallbacks.length > 0) {
494
- try {
495
- await Promise.all(window.__completionCallbacks.map(cb => cb(true)));
496
- } catch (e) {
497
- console.error('Completion callback error:', e);
498
- }
499
- }
500
-
501
- await window.complete(null, returnValue);
502
- } catch (error) {
503
-
504
- // Call completion callbacks before complete() (error path)
505
- if (window.__completionCallbacks && window.__completionCallbacks.length > 0) {
506
- try {
507
- await Promise.all(window.__completionCallbacks.map(cb => cb(false)));
508
- } catch (e) {
509
- console.error('Completion callback error:', e);
510
- }
511
- }
512
-
513
- await window.complete({
514
- message: error?.message || String(error),
515
- stack: error?.stack || new Error().stack
516
- });
517
- }
518
- })();
519
- </script>
520
- </body>
521
- </html>`;
522
- }
523
- }
524
-
525
- /**
526
- * Generate runtime script from providers
527
- * @param sandboxId Unique sandbox ID
528
- * @param providers Runtime providers
529
- * @param isStandalone If true, skip runtime bridge and navigation interceptor (for standalone downloads)
530
- */
531
- private getRuntimeScript(
532
- sandboxId: string,
533
- providers: SandboxRuntimeProvider[] = [],
534
- isStandalone: boolean = false,
535
- ): string {
536
- // Collect all data from providers
537
- const allData: Record<string, unknown> = {};
538
- for (const provider of providers) {
539
- Object.assign(allData, provider.getData());
540
- }
541
-
542
- // Generate bridge code (skip if standalone)
543
- const bridgeCode = isStandalone
544
- ? ""
545
- : RuntimeMessageBridge.generateBridgeCode({
546
- context: "sandbox-iframe",
547
- sandboxId,
548
- });
549
-
550
- // Collect all runtime functions - pass sandboxId as string literal
551
- const runtimeFunctions: string[] = [];
552
- for (const provider of providers) {
553
- runtimeFunctions.push(`(${provider.getRuntime().toString()})(${JSON.stringify(sandboxId)});`);
554
- }
555
-
556
- // Build script with HTML escaping
557
- // Escape </script> to prevent premature tag closure in HTML parser
558
- const dataInjection = Object.entries(allData)
559
- .map(([key, value]) => {
560
- const jsonStr = JSON.stringify(value).replace(/<\/script/gi, "<\\/script");
561
- return `window.${key} = ${jsonStr};`;
562
- })
563
- .join("\n");
564
-
565
- // TODO the font-size is needed, as chrome seems to inject a stylesheet into iframes
566
- // found in an extension context like sidepanel, setting body { font-size: 75% }. It's
567
- // definitely not our code doing that.
568
- // See https://stackoverflow.com/questions/71480433/chrome-is-injecting-some-stylesheet-in-popup-ui-which-reduces-the-font-size-to-7
569
-
570
- // Navigation interceptor (only if NOT standalone)
571
- const navigationInterceptor = isStandalone
572
- ? ""
573
- : `
574
- // Navigation interceptor: prevent all navigation and open externally
575
- (function() {
576
- // Intercept link clicks
577
- document.addEventListener('click', function(e) {
578
- const link = e.target.closest('a');
579
- if (link && link.href) {
580
- // Check if it's an external link (not javascript: or #hash)
581
- if (link.href.startsWith('http://') || link.href.startsWith('https://')) {
582
- e.preventDefault();
583
- e.stopPropagation();
584
- window.parent.postMessage({ type: 'open-external-url', url: link.href }, '*');
585
- }
586
- }
587
- }, true);
588
-
589
- // Intercept form submissions
590
- document.addEventListener('submit', function(e) {
591
- const form = e.target;
592
- if (form && form.action) {
593
- e.preventDefault();
594
- e.stopPropagation();
595
- window.parent.postMessage({ type: 'open-external-url', url: form.action }, '*');
596
- }
597
- }, true);
598
-
599
- // Prevent window.location changes (only if not already redefined)
600
- try {
601
- const originalLocation = window.location;
602
- Object.defineProperty(window, 'location', {
603
- get: function() { return originalLocation; },
604
- set: function(url) {
605
- window.parent.postMessage({ type: 'open-external-url', url: url.toString() }, '*');
606
- }
607
- });
608
- } catch (e) {
609
- // Already defined, skip
610
- }
611
- })();
612
- `;
613
-
614
- return `<style>
615
- html, body {
616
- font-size: initial;
617
- }
618
- </style>
619
- <script>
620
- window.sandboxId = ${JSON.stringify(sandboxId)};
621
- ${dataInjection}
622
- ${bridgeCode}
623
- ${runtimeFunctions.join("\n")}
624
- ${navigationInterceptor}
625
- </script>`;
626
- }
627
- }