@frontmcp/uipack 1.10.8 → 1.10.9-rc.2

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.
@@ -1,84 +1,4 @@
1
- // libs/uipack/src/bridge-runtime/iife-generator.ts
2
- var WIDGET_CALL_META_KEY = "frontmcp/widgetCall";
3
- var MCP_APPS_DISPLAY_MODES = ["inline", "fullscreen", "pip"];
4
- function generateBridgeIIFE(options = {}) {
5
- const { debug = false, trustedOrigins = [], minify = false } = options;
6
- const adapters = options.adapters || ["openai", "ext-apps", "claude", "gemini", "generic"];
7
- const parts = [];
8
- parts.push("(function() {");
9
- parts.push('"use strict";');
10
- parts.push("");
11
- if (debug) {
12
- parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }');
13
- } else {
14
- parts.push("function log() {}");
15
- }
16
- parts.push("");
17
- parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");
18
- parts.push("");
19
- parts.push(generateContextDetection());
20
- parts.push("");
21
- parts.push(generateBaseCapabilities());
22
- parts.push("");
23
- if (adapters.includes("openai")) {
24
- parts.push(generateOpenAIAdapter());
25
- parts.push("");
26
- }
27
- if (adapters.includes("ext-apps")) {
28
- parts.push(generateExtAppsAdapter(trustedOrigins));
29
- parts.push("");
30
- }
31
- if (adapters.includes("claude")) {
32
- parts.push(generateClaudeAdapter());
33
- parts.push("");
34
- }
35
- if (adapters.includes("gemini")) {
36
- parts.push(generateGeminiAdapter());
37
- parts.push("");
38
- }
39
- if (adapters.includes("generic")) {
40
- parts.push(generateGenericAdapter());
41
- parts.push("");
42
- }
43
- parts.push(generatePlatformDetection(adapters));
44
- parts.push("");
45
- parts.push(generateBridgeClass());
46
- parts.push("");
47
- parts.push("var bridge = new FrontMcpBridge();");
48
- parts.push("bridge.initialize().then(function() {");
49
- parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');
50
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');
51
- parts.push(" if (window.__mcpDisplayMode) bridge.requestDisplayMode(window.__mcpDisplayMode).catch(function() {});");
52
- parts.push("}).catch(function(err) {");
53
- parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');
54
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');
55
- parts.push("});");
56
- parts.push("");
57
- parts.push("window.FrontMcpBridge = bridge;");
58
- parts.push("");
59
- parts.push(generateAutoResize());
60
- parts.push("function __showLoading() {");
61
- parts.push(' var root = document.getElementById("root");');
62
- parts.push(" if (root && !root.hasChildNodes()) {");
63
- parts.push(
64
- ` root.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;padding:2rem;color:#6b7280;font-family:system-ui,sans-serif"><div style="text-align:center"><div style="width:24px;height:24px;border:2px solid #e5e7eb;border-top-color:#3b82f6;border-radius:50%;animation:__spin 0.6s linear infinite;margin:0 auto 12px"></div><div style="font-size:0.875rem">Loading widget...</div></div></div><style>@keyframes __spin{to{transform:rotate(360deg)}}</style>';`
65
- );
66
- parts.push(" }");
67
- parts.push("}");
68
- parts.push('if (document.readyState === "loading") {');
69
- parts.push(' document.addEventListener("DOMContentLoaded", __showLoading);');
70
- parts.push("} else {");
71
- parts.push(" __showLoading();");
72
- parts.push("}");
73
- parts.push("})();");
74
- const code = parts.join("\n");
75
- if (minify) {
76
- return minifyJS(code);
77
- }
78
- return code;
79
- }
80
- function generateAutoResize() {
81
- return `
1
+ var WIDGET_CALL_META_KEY="frontmcp/widgetCall";var MCP_APPS_DISPLAY_MODES=["inline","fullscreen","pip"];function generateBridgeIIFE(options={}){const{debug=false,trustedOrigins=[],minify=false}=options;const adapters=options.adapters||["openai","ext-apps","claude","gemini","generic"];const parts=[];parts.push("(function() {");parts.push('"use strict";');parts.push("");if(debug){parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }')}else{parts.push("function log() {}")}parts.push("");parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");parts.push("");parts.push(generateContextDetection());parts.push("");parts.push(generateBaseCapabilities());parts.push("");if(adapters.includes("openai")){parts.push(generateOpenAIAdapter());parts.push("")}if(adapters.includes("ext-apps")){parts.push(generateExtAppsAdapter(trustedOrigins));parts.push("")}if(adapters.includes("claude")){parts.push(generateClaudeAdapter());parts.push("")}if(adapters.includes("gemini")){parts.push(generateGeminiAdapter());parts.push("")}if(adapters.includes("generic")){parts.push(generateGenericAdapter());parts.push("")}parts.push(generatePlatformDetection(adapters));parts.push("");parts.push(generateBridgeClass());parts.push("");parts.push("var bridge = new FrontMcpBridge();");parts.push("bridge.initialize().then(function() {");parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');parts.push(" if (window.__mcpDisplayMode) bridge.requestDisplayMode(window.__mcpDisplayMode).catch(function() {});");parts.push("}).catch(function(err) {");parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');parts.push("});");parts.push("");parts.push("window.FrontMcpBridge = bridge;");parts.push("");parts.push(generateAutoResize());parts.push("function __showLoading() {");parts.push(' var root = document.getElementById("root");');parts.push(" if (root && !root.hasChildNodes()) {");parts.push(` root.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;padding:2rem;color:#6b7280;font-family:system-ui,sans-serif"><div style="text-align:center"><div style="width:24px;height:24px;border:2px solid #e5e7eb;border-top-color:#3b82f6;border-radius:50%;animation:__spin 0.6s linear infinite;margin:0 auto 12px"></div><div style="font-size:0.875rem">Loading widget...</div></div></div><style>@keyframes __spin{to{transform:rotate(360deg)}}</style>';`);parts.push(" }");parts.push("}");parts.push('if (document.readyState === "loading") {');parts.push(' document.addEventListener("DOMContentLoaded", __showLoading);');parts.push("} else {");parts.push(" __showLoading();");parts.push("}");parts.push("})();");const code=parts.join("\n");if(minify){return minifyJS(code)}return code}function generateAutoResize(){return`
82
2
  function __applySizingCss(sizing) {
83
3
  if (typeof document === 'undefined' || !document.documentElement) return;
84
4
  function toLen(v) { return typeof v === 'number' ? v + 'px' : v; }
@@ -213,10 +133,7 @@ function __initAutoResize() {
213
133
  }
214
134
  }
215
135
  __initAutoResize();
216
- `.trim();
217
- }
218
- function generateContextDetection() {
219
- return `
136
+ `.trim()}function generateContextDetection(){return`
220
137
  function detectTheme() {
221
138
  if (typeof window !== 'undefined' && window.matchMedia) {
222
139
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
@@ -303,10 +220,7 @@ function readInjectedData() {
303
220
  }
304
221
  return data;
305
222
  }
306
- `.trim();
307
- }
308
- function generateBaseCapabilities() {
309
- return `
223
+ `.trim()}function generateBaseCapabilities(){return`
310
224
  var DEFAULT_CAPABILITIES = {
311
225
  canCallTools: false,
312
226
  canSendMessages: false,
@@ -316,10 +230,7 @@ var DEFAULT_CAPABILITIES = {
316
230
  supportsDisplayModes: false,
317
231
  supportsTheme: true
318
232
  };
319
- `.trim();
320
- }
321
- function generateOpenAIAdapter() {
322
- return `
233
+ `.trim()}function generateOpenAIAdapter(){return`
323
234
  var OpenAIAdapter = {
324
235
  id: 'openai',
325
236
  name: 'OpenAI ChatGPT',
@@ -404,11 +315,7 @@ var OpenAIAdapter = {
404
315
  return Promise.resolve();
405
316
  }
406
317
  };
407
- `.trim();
408
- }
409
- function generateExtAppsAdapter(trustedOrigins) {
410
- const originsArray = trustedOrigins.length > 0 ? JSON.stringify(trustedOrigins) : "[]";
411
- return `
318
+ `.trim()}function generateExtAppsAdapter(trustedOrigins){const originsArray=trustedOrigins.length>0?JSON.stringify(trustedOrigins):"[]";return`
412
319
  var ExtAppsAdapter = {
413
320
  id: 'ext-apps',
414
321
  name: 'ext-apps (SEP-1865)',
@@ -751,10 +658,7 @@ var ExtAppsAdapter = {
751
658
  return this.sendRequest('ui/unregisterTool', { name: name });
752
659
  }
753
660
  };
754
- `.trim();
755
- }
756
- function generateClaudeAdapter() {
757
- return `
661
+ `.trim()}function generateClaudeAdapter(){return`
758
662
  var ClaudeAdapter = {
759
663
  id: 'claude',
760
664
  name: 'Claude (Anthropic)',
@@ -815,10 +719,7 @@ var ClaudeAdapter = {
815
719
  return Promise.resolve();
816
720
  }
817
721
  };
818
- `.trim();
819
- }
820
- function generateGeminiAdapter() {
821
- return `
722
+ `.trim()}function generateGeminiAdapter(){return`
822
723
  var GeminiAdapter = {
823
724
  id: 'gemini',
824
725
  name: 'Google Gemini',
@@ -869,10 +770,7 @@ var GeminiAdapter = {
869
770
  return Promise.resolve();
870
771
  }
871
772
  };
872
- `.trim();
873
- }
874
- function generateGenericAdapter() {
875
- return `
773
+ `.trim()}function generateGenericAdapter(){return`
876
774
  var GenericAdapter = {
877
775
  id: 'generic',
878
776
  name: 'Generic Web',
@@ -907,26 +805,7 @@ var GenericAdapter = {
907
805
  return Promise.resolve();
908
806
  }
909
807
  };
910
- `.trim();
911
- }
912
- function generatePlatformDetection(adapters) {
913
- const adapterVars = adapters.map((a) => {
914
- switch (a) {
915
- case "openai":
916
- return "OpenAIAdapter";
917
- case "ext-apps":
918
- return "ExtAppsAdapter";
919
- case "claude":
920
- return "ClaudeAdapter";
921
- case "gemini":
922
- return "GeminiAdapter";
923
- case "generic":
924
- return "GenericAdapter";
925
- default:
926
- return "";
927
- }
928
- }).filter(Boolean);
929
- return `
808
+ `.trim()}function generatePlatformDetection(adapters){const adapterVars=adapters.map(a=>{switch(a){case"openai":return"OpenAIAdapter";case"ext-apps":return"ExtAppsAdapter";case"claude":return"ClaudeAdapter";case"gemini":return"GeminiAdapter";case"generic":return"GenericAdapter";default:return""}}).filter(Boolean);return`
930
809
  var ADAPTERS = [${adapterVars.join(", ")}].sort(function(a, b) { return b.priority - a.priority; });
931
810
 
932
811
  function detectPlatform() {
@@ -939,10 +818,7 @@ function detectPlatform() {
939
818
  log('No platform detected, using generic');
940
819
  return GenericAdapter;
941
820
  }
942
- `.trim();
943
- }
944
- function generateBridgeClass() {
945
- return `
821
+ `.trim()}function generateBridgeClass(){return`
946
822
  function FrontMcpBridge() {
947
823
  this._adapter = null;
948
824
  this._initialized = false;
@@ -1318,626 +1194,16 @@ FrontMcpBridge.prototype._setupDataToolCallHandler = function() {
1318
1194
  }
1319
1195
  }, true); // Use capture phase to handle before React handlers
1320
1196
  };
1321
- `.trim();
1322
- }
1323
- var MAX_MINIFY_CODE_LENGTH = 5e5;
1324
- function minifyJS(code) {
1325
- if (code.length > MAX_MINIFY_CODE_LENGTH) {
1326
- return code;
1327
- }
1328
- const out = [];
1329
- let inBlockComment = false;
1330
- for (const raw of code.split("\n")) {
1331
- const line = raw.trim();
1332
- if (inBlockComment) {
1333
- if (line.includes("*/")) inBlockComment = false;
1334
- continue;
1335
- }
1336
- if (line === "" || line.startsWith("//")) continue;
1337
- if (line.startsWith("/*")) {
1338
- if (!line.includes("*/")) inBlockComment = true;
1339
- continue;
1340
- }
1341
- out.push(line);
1342
- }
1343
- return out.join("\n");
1344
- }
1345
- function generatePlatformBundle(platform, options = {}) {
1346
- const platformAdapters = {
1347
- chatgpt: ["openai", "generic"],
1348
- claude: ["claude", "generic"],
1349
- gemini: ["gemini", "generic"],
1350
- universal: ["openai", "ext-apps", "claude", "gemini", "generic"]
1351
- };
1352
- return generateBridgeIIFE({
1353
- ...options,
1354
- adapters: platformAdapters[platform]
1355
- });
1356
- }
1357
- var UNIVERSAL_BRIDGE_SCRIPT = generateBridgeIIFE();
1358
- var BRIDGE_SCRIPT_TAGS = {
1359
- universal: `<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,
1360
- chatgpt: `<script>${generatePlatformBundle("chatgpt")}</script>`,
1361
- claude: `<script>${generatePlatformBundle("claude")}</script>`,
1362
- gemini: `<script>${generatePlatformBundle("gemini")}</script>`
1363
- };
1364
-
1365
- // libs/uipack/src/shell/csp.ts
1366
- var DEFAULT_CDN_DOMAINS = [
1367
- "https://cdn.jsdelivr.net",
1368
- "https://cdnjs.cloudflare.com",
1369
- "https://fonts.googleapis.com",
1370
- "https://fonts.gstatic.com",
1371
- "https://esm.sh"
1372
- ];
1373
- var DEFAULT_CSP_DIRECTIVES = [
1374
- "default-src 'none'",
1375
- `script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1376
- `style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1377
- `img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1378
- `font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1379
- `connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,
1380
- "object-src 'self' data:"
1381
- ];
1382
- var RESTRICTIVE_CSP_DIRECTIVES = [
1383
- "default-src 'none'",
1384
- "script-src 'self' 'unsafe-inline'",
1385
- "style-src 'self' 'unsafe-inline'",
1386
- "img-src 'self' data:",
1387
- "font-src 'self' data:",
1388
- "connect-src 'none'",
1389
- "object-src 'self' data:"
1390
- ];
1391
- function buildCSPDirectives(csp) {
1392
- if (!csp) {
1393
- return [...DEFAULT_CSP_DIRECTIVES];
1394
- }
1395
- const validResourceDomains = sanitizeCSPDomains(csp.resourceDomains);
1396
- const validConnectDomains = sanitizeCSPDomains(csp.connectDomains);
1397
- const allResourceDomains = [.../* @__PURE__ */ new Set([...DEFAULT_CDN_DOMAINS, ...validResourceDomains])];
1398
- const directives = [
1399
- "default-src 'none'",
1400
- `script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,
1401
- `style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`
1402
- ];
1403
- const imgSources = ["'self'", "data:", ...allResourceDomains];
1404
- directives.push(`img-src ${imgSources.join(" ")}`);
1405
- const fontSources = ["'self'", "data:", ...allResourceDomains];
1406
- directives.push(`font-src ${fontSources.join(" ")}`);
1407
- const connectSources = [.../* @__PURE__ */ new Set([...allResourceDomains, ...validConnectDomains])];
1408
- directives.push(`connect-src ${connectSources.join(" ")}`);
1409
- directives.push("object-src 'self' data:");
1410
- return directives;
1411
- }
1412
- function buildCSPMetaTag(csp) {
1413
- const directives = buildCSPDirectives(csp);
1414
- const content = directives.join("; ");
1415
- return `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`;
1416
- }
1417
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
1418
- function validateCSPDomain(domain) {
1419
- if (typeof domain !== "string" || /[\s;,'"]/.test(domain)) return false;
1420
- if (/[?#]/.test(domain)) return false;
1421
- if (domain.includes("*")) {
1422
- const wildcard = /^(?:https|wss):\/\/\*\.(.*)$/.exec(domain);
1423
- return wildcard !== null && /^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(wildcard[1]);
1424
- }
1425
- try {
1426
- const url = new URL(domain);
1427
- if (url.protocol === "https:" || url.protocol === "wss:") return true;
1428
- return (url.protocol === "http:" || url.protocol === "ws:") && LOOPBACK_HOSTS.has(url.hostname);
1429
- } catch {
1430
- return false;
1431
- }
1432
- }
1433
- var reportedInvalidDomains = /* @__PURE__ */ new Set();
1434
- function sanitizeCSPDomains(domains) {
1435
- if (!domains) return [];
1436
- const valid = [];
1437
- for (const domain of domains) {
1438
- if (validateCSPDomain(domain)) {
1439
- valid.push(domain);
1440
- } else if (!reportedInvalidDomains.has(domain)) {
1441
- reportedInvalidDomains.add(domain);
1442
- console.warn(
1443
- `Invalid CSP domain ignored: ${domain} (expected an https:// or wss:// origin, or http:// / ws:// on localhost)`
1444
- );
1445
- }
1446
- }
1447
- return valid;
1448
- }
1449
- function escapeAttribute(str) {
1450
- return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1451
- }
1452
-
1453
- // libs/uipack/src/shell/custom-shell-types.ts
1454
- var SHELL_PLACEHOLDER_NAMES = ["CSP", "DATA", "BRIDGE", "CONTENT", "TITLE"];
1455
- var SHELL_PLACEHOLDERS = {
1456
- CSP: "{{CSP}}",
1457
- DATA: "{{DATA}}",
1458
- BRIDGE: "{{BRIDGE}}",
1459
- CONTENT: "{{CONTENT}}",
1460
- TITLE: "{{TITLE}}"
1461
- };
1462
- var REQUIRED_PLACEHOLDERS = ["CONTENT"];
1463
- var OPTIONAL_PLACEHOLDERS = ["CSP", "DATA", "BRIDGE", "TITLE"];
1464
- function isInlineShellSource(source) {
1465
- return typeof source === "object" && source !== null && "inline" in source;
1466
- }
1467
- function isUrlShellSource(source) {
1468
- return typeof source === "object" && source !== null && "url" in source;
1469
- }
1470
- function isNpmShellSource(source) {
1471
- return typeof source === "object" && source !== null && "npm" in source;
1472
- }
1473
-
1474
- // libs/uipack/src/shell/custom-shell-applier.ts
1475
- var PLACEHOLDER_PATTERN = new RegExp(`\\{\\{(${SHELL_PLACEHOLDER_NAMES.join("|")})\\}\\}`, "g");
1476
- var VALUE_KEYS = {
1477
- CSP: "csp",
1478
- DATA: "data",
1479
- BRIDGE: "bridge",
1480
- CONTENT: "content",
1481
- TITLE: "title"
1482
- };
1483
- function applyShellTemplate(template, values) {
1484
- return template.replace(PLACEHOLDER_PATTERN, (_token, name) => values[VALUE_KEYS[name]]);
1485
- }
1486
-
1487
- // libs/uipack/src/shell/custom-shell-validator.ts
1488
- function validateShellTemplate(template) {
1489
- const found = {};
1490
- for (const name of SHELL_PLACEHOLDER_NAMES) {
1491
- found[name] = template.includes(SHELL_PLACEHOLDERS[name]);
1492
- }
1493
- const missingRequired = REQUIRED_PLACEHOLDERS.filter((name) => !found[name]);
1494
- const missingOptional = OPTIONAL_PLACEHOLDERS.filter((name) => !found[name]);
1495
- return {
1496
- valid: missingRequired.length === 0,
1497
- found,
1498
- missingRequired,
1499
- missingOptional
1500
- };
1501
- }
1502
-
1503
- // libs/uipack/src/utils/index.ts
1504
- function escapeHtml(str) {
1505
- if (str === null || str === void 0) {
1506
- return "";
1507
- }
1508
- const s = String(str);
1509
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1510
- }
1511
- var SCRIPT_UNSAFE_CHARACTERS = /[<>&\u2028\u2029]/g;
1512
- function toUnicodeEscape(character) {
1513
- return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
1514
- }
1515
- function safeJsonForScript(value) {
1516
- if (value === void 0) {
1517
- return "null";
1518
- }
1519
- try {
1520
- const jsonString = JSON.stringify(value, (_key, val) => {
1521
- if (typeof val === "bigint") {
1522
- return val.toString();
1523
- }
1524
- return val;
1525
- });
1526
- if (jsonString === void 0) {
1527
- return "null";
1528
- }
1529
- return jsonString.replace(SCRIPT_UNSAFE_CHARACTERS, toUnicodeEscape);
1530
- } catch {
1531
- return '{"error":"Value could not be serialized"}';
1532
- }
1533
- }
1534
-
1535
- // libs/uipack/src/shell/trusted-html.ts
1536
- var TRUSTED_HTML = /* @__PURE__ */ Symbol.for("@frontmcp/uipack/trusted-html");
1537
- function trustedHtml(markup) {
1538
- const value = String(markup);
1539
- return Object.freeze({ [TRUSTED_HTML]: value, toString: () => value });
1540
- }
1541
- function isTrustedHtml(value) {
1542
- return typeof value === "object" && value !== null && typeof value[TRUSTED_HTML] === "string";
1543
- }
1544
- function interpolate(value) {
1545
- if (isTrustedHtml(value)) return value[TRUSTED_HTML];
1546
- if (Array.isArray(value)) return value.map(interpolate).join("");
1547
- if (value === false) return "";
1548
- return escapeHtml(value);
1549
- }
1550
- function html(strings, ...values) {
1551
- let markup = strings[0];
1552
- for (let index = 0; index < values.length; index++) {
1553
- markup += interpolate(values[index]) + strings[index + 1];
1554
- }
1555
- return trustedHtml(markup);
1556
- }
1557
-
1558
- // libs/uipack/src/shell/data-injector.ts
1559
- function hasSizing(sizing) {
1560
- if (!sizing) return false;
1561
- return sizing.preferredHeight !== void 0 || sizing.minHeight !== void 0 || sizing.maxHeight !== void 0 || sizing.aspectRatio !== void 0 || sizing.autoResize !== void 0;
1562
- }
1563
- function buildDataInjectionScript(options) {
1564
- const { toolName, input, output, structuredContent, sizing, displayMode } = options;
1565
- const lines = [
1566
- `window.__mcpAppsEnabled = true;`,
1567
- `window.__mcpToolName = ${safeJsonForScript(toolName)};`,
1568
- `window.__mcpToolInput = ${safeJsonForScript(input ?? null)};`,
1569
- `window.__mcpToolOutput = ${safeJsonForScript(output ?? null)};`,
1570
- `window.__mcpStructuredContent = ${safeJsonForScript(structuredContent ?? null)};`
1571
- ];
1572
- if (hasSizing(sizing)) {
1573
- lines.push(`window.__mcpWidgetSizing = ${safeJsonForScript(sizing)};`);
1574
- }
1575
- if (displayMode && displayMode !== "inline") {
1576
- lines.push(`window.__mcpDisplayMode = ${safeJsonForScript(displayMode)};`);
1577
- }
1578
- return `<script>
1197
+ `.trim()}var MAX_MINIFY_CODE_LENGTH=5e5;function minifyJS(code){if(code.length>MAX_MINIFY_CODE_LENGTH){return code}const out=[];let inBlockComment=false;for(const raw of code.split("\n")){const line=raw.trim();if(inBlockComment){if(line.includes("*/"))inBlockComment=false;continue}if(line===""||line.startsWith("//"))continue;if(line.startsWith("/*")){if(!line.includes("*/"))inBlockComment=true;continue}out.push(line)}return out.join("\n")}function generatePlatformBundle(platform,options={}){const platformAdapters={chatgpt:["openai","generic"],claude:["claude","generic"],gemini:["gemini","generic"],universal:["openai","ext-apps","claude","gemini","generic"]};return generateBridgeIIFE({...options,adapters:platformAdapters[platform]})}var UNIVERSAL_BRIDGE_SCRIPT=generateBridgeIIFE();var BRIDGE_SCRIPT_TAGS={universal:`<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,chatgpt:`<script>${generatePlatformBundle("chatgpt")}</script>`,claude:`<script>${generatePlatformBundle("claude")}</script>`,gemini:`<script>${generatePlatformBundle("gemini")}</script>`};var DEFAULT_CDN_DOMAINS=["https://cdn.jsdelivr.net","https://cdnjs.cloudflare.com","https://fonts.googleapis.com","https://fonts.gstatic.com","https://esm.sh"];var DEFAULT_CSP_DIRECTIVES=["default-src 'none'",`script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,`style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,`img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,`font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,`connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,"object-src 'self' data:"];var RESTRICTIVE_CSP_DIRECTIVES=["default-src 'none'","script-src 'self' 'unsafe-inline'","style-src 'self' 'unsafe-inline'","img-src 'self' data:","font-src 'self' data:","connect-src 'none'","object-src 'self' data:"];function buildCSPDirectives(csp){if(!csp){return[...DEFAULT_CSP_DIRECTIVES]}const validResourceDomains=sanitizeCSPDomains(csp.resourceDomains);const validConnectDomains=sanitizeCSPDomains(csp.connectDomains);const allResourceDomains=[...new Set([...DEFAULT_CDN_DOMAINS,...validResourceDomains])];const directives=["default-src 'none'",`script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,`style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`];const imgSources=["'self'","data:",...allResourceDomains];directives.push(`img-src ${imgSources.join(" ")}`);const fontSources=["'self'","data:",...allResourceDomains];directives.push(`font-src ${fontSources.join(" ")}`);const connectSources=[...new Set([...allResourceDomains,...validConnectDomains])];directives.push(`connect-src ${connectSources.join(" ")}`);directives.push("object-src 'self' data:");return directives}function buildCSPMetaTag(csp){const directives=buildCSPDirectives(csp);const content=directives.join("; ");return`<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function validateCSPDomain(domain){if(typeof domain!=="string"||/[\s;,'"]/.test(domain))return false;if(/[?#]/.test(domain))return false;if(domain.includes("*")){const wildcard=/^(?:https|wss):\/\/\*\.(.*)$/.exec(domain);return wildcard!==null&&/^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(wildcard[1])}try{const url=new URL(domain);if(url.protocol==="https:"||url.protocol==="wss:")return true;return(url.protocol==="http:"||url.protocol==="ws:")&&LOOPBACK_HOSTS.has(url.hostname)}catch{return false}}var reportedInvalidDomains=new Set;function sanitizeCSPDomains(domains){if(!domains)return[];const valid=[];for(const domain of domains){if(validateCSPDomain(domain)){valid.push(domain)}else if(!reportedInvalidDomains.has(domain)){reportedInvalidDomains.add(domain);console.warn(`Invalid CSP domain ignored: ${domain} (expected an https:// or wss:// origin, or http:// / ws:// on localhost)`)}}return valid}function escapeAttribute(str){return str.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var SHELL_PLACEHOLDER_NAMES=["CSP","DATA","BRIDGE","CONTENT","TITLE"];var SHELL_PLACEHOLDERS={CSP:"{{CSP}}",DATA:"{{DATA}}",BRIDGE:"{{BRIDGE}}",CONTENT:"{{CONTENT}}",TITLE:"{{TITLE}}"};var REQUIRED_PLACEHOLDERS=["CONTENT"];var OPTIONAL_PLACEHOLDERS=["CSP","DATA","BRIDGE","TITLE"];function isInlineShellSource(source){return typeof source==="object"&&source!==null&&"inline"in source}function isUrlShellSource(source){return typeof source==="object"&&source!==null&&"url"in source}function isNpmShellSource(source){return typeof source==="object"&&source!==null&&"npm"in source}var PLACEHOLDER_PATTERN=new RegExp(`\\{\\{(${SHELL_PLACEHOLDER_NAMES.join("|")})\\}\\}`,"g");var VALUE_KEYS={CSP:"csp",DATA:"data",BRIDGE:"bridge",CONTENT:"content",TITLE:"title"};function applyShellTemplate(template,values){return template.replace(PLACEHOLDER_PATTERN,(_token,name)=>values[VALUE_KEYS[name]])}function validateShellTemplate(template){const found={};for(const name of SHELL_PLACEHOLDER_NAMES){found[name]=template.includes(SHELL_PLACEHOLDERS[name])}const missingRequired=REQUIRED_PLACEHOLDERS.filter(name=>!found[name]);const missingOptional=OPTIONAL_PLACEHOLDERS.filter(name=>!found[name]);return{valid:missingRequired.length===0,found,missingRequired,missingOptional}}function escapeHtml(str){if(str===null||str===void 0){return""}const s=String(str);return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}var SCRIPT_UNSAFE_CHARACTERS=/[<>&\u2028\u2029]/g;function toUnicodeEscape(character){return`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`}function safeJsonForScript(value){if(value===void 0){return"null"}try{const jsonString=JSON.stringify(value,(_key,val)=>{if(typeof val==="bigint"){return val.toString()}return val});if(jsonString===void 0){return"null"}return jsonString.replace(SCRIPT_UNSAFE_CHARACTERS,toUnicodeEscape)}catch{return'{"error":"Value could not be serialized"}'}}var TRUSTED_HTML=Symbol.for("@frontmcp/uipack/trusted-html");function trustedHtml(markup){const value=String(markup);return Object.freeze({[TRUSTED_HTML]:value,toString:()=>value})}function isTrustedHtml(value){return typeof value==="object"&&value!==null&&typeof value[TRUSTED_HTML]==="string"}function interpolate(value){if(isTrustedHtml(value))return value[TRUSTED_HTML];if(Array.isArray(value))return value.map(interpolate).join("");if(value===false)return"";return escapeHtml(value)}function html(strings,...values){let markup=strings[0];for(let index=0;index<values.length;index++){markup+=interpolate(values[index])+strings[index+1]}return trustedHtml(markup)}function hasSizing(sizing){if(!sizing)return false;return sizing.preferredHeight!==void 0||sizing.minHeight!==void 0||sizing.maxHeight!==void 0||sizing.aspectRatio!==void 0||sizing.autoResize!==void 0}function buildDataInjectionScript(options){const{toolName,input,output,structuredContent,sizing,displayMode}=options;const lines=[`window.__mcpAppsEnabled = true;`,`window.__mcpToolName = ${safeJsonForScript(toolName)};`,`window.__mcpToolInput = ${safeJsonForScript(input??null)};`,`window.__mcpToolOutput = ${safeJsonForScript(output??null)};`,`window.__mcpStructuredContent = ${safeJsonForScript(structuredContent??null)};`];if(hasSizing(sizing)){lines.push(`window.__mcpWidgetSizing = ${safeJsonForScript(sizing)};`)}if(displayMode&&displayMode!=="inline"){lines.push(`window.__mcpDisplayMode = ${safeJsonForScript(displayMode)};`)}return`<script>
1579
1198
  ${lines.join("\n")}
1580
- </script>`;
1581
- }
1582
- function buildCustomDataInjectionScript(descriptor) {
1583
- if (descriptor.script !== void 0) {
1584
- return descriptor.script;
1585
- }
1586
- if (descriptor.globalKey !== void 0) {
1587
- return `<script>window[${safeJsonForScript(descriptor.globalKey)}] = ${safeJsonForScript(
1588
- descriptor.value ?? null
1589
- )};</script>`;
1590
- }
1591
- return "";
1592
- }
1593
- var _uniqueIdCounter = 0;
1594
- function createTemplateHelpers() {
1595
- return {
1596
- escapeHtml: (str) => escapeHtml(str),
1597
- formatDate: (date, format) => {
1598
- const d = date instanceof Date ? date : new Date(date);
1599
- if (isNaN(d.getTime())) return String(date);
1600
- if (format === "iso") return d.toISOString();
1601
- if (format === "date") return d.toLocaleDateString();
1602
- if (format === "time") return d.toLocaleTimeString();
1603
- return d.toLocaleString();
1604
- },
1605
- formatCurrency: (amount, currency = "USD") => {
1606
- return new Intl.NumberFormat("en-US", {
1607
- style: "currency",
1608
- currency
1609
- }).format(amount);
1610
- },
1611
- uniqueId: (prefix = "mcp") => {
1612
- return `${prefix}-${++_uniqueIdCounter}`;
1613
- },
1614
- jsonEmbed: (data) => safeJsonForScript(data),
1615
- html,
1616
- trustedHtml
1617
- };
1618
- }
1619
-
1620
- // libs/uipack/src/shell/sizing-css.ts
1621
- function sanitizeCssValue(value) {
1622
- return value.replace(/[<>{};]/g, "").trim();
1623
- }
1624
- function toCssLength(value) {
1625
- return typeof value === "number" ? `${value}px` : sanitizeCssValue(value);
1626
- }
1627
- function buildSizingStyleTag(sizing) {
1628
- if (!hasSizing(sizing)) return "";
1629
- const hasCssSizing = sizing.preferredHeight !== void 0 || sizing.minHeight !== void 0 || sizing.maxHeight !== void 0 || sizing.aspectRatio !== void 0;
1630
- if (!hasCssSizing) return "";
1631
- const rootRules = [];
1632
- const docRules = ["margin: 0;"];
1633
- if (sizing.preferredHeight !== void 0) {
1634
- const h = toCssLength(sizing.preferredHeight);
1635
- docRules.push(`height: ${h};`);
1636
- rootRules.push(`min-height: ${h};`);
1637
- }
1638
- if (sizing.minHeight !== void 0) {
1639
- const mh = toCssLength(sizing.minHeight);
1640
- docRules.push(`min-height: ${mh};`);
1641
- rootRules.push(`min-height: ${mh};`);
1642
- }
1643
- if (sizing.maxHeight !== void 0) {
1644
- const mx = toCssLength(sizing.maxHeight);
1645
- docRules.push(`max-height: ${mx};`);
1646
- rootRules.push(`max-height: ${mx};`);
1647
- }
1648
- if (sizing.aspectRatio !== void 0) {
1649
- const ar = typeof sizing.aspectRatio === "number" ? String(sizing.aspectRatio) : sanitizeCssValue(sizing.aspectRatio);
1650
- if (ar) rootRules.push(`aspect-ratio: ${ar};`);
1651
- }
1652
- const parts = [`html, body { ${docRules.join(" ")} }`];
1653
- if (rootRules.length > 0) {
1654
- parts.push(`#root { ${rootRules.join(" ")} }`);
1655
- }
1656
- return `<style>${parts.join("\n")}</style>`;
1657
- }
1658
-
1659
- // libs/uipack/src/shell/builder.ts
1660
- function resolveDataInjectionScript(args) {
1661
- if (args.dataInjection) {
1662
- return buildCustomDataInjectionScript(args.dataInjection);
1663
- }
1664
- return buildDataInjectionScript({
1665
- toolName: args.toolName,
1666
- input: args.input,
1667
- output: args.output,
1668
- structuredContent: args.structuredContent,
1669
- sizing: args.sizing,
1670
- displayMode: args.displayMode
1671
- });
1672
- }
1673
- function buildShell(content, config) {
1674
- const {
1675
- toolName,
1676
- csp,
1677
- withShell = true,
1678
- input,
1679
- output,
1680
- structuredContent,
1681
- includeBridge = true,
1682
- title,
1683
- sizing,
1684
- displayMode
1685
- } = config;
1686
- const { customShell, dataInjection } = config;
1687
- const dataScript = resolveDataInjectionScript({
1688
- dataInjection,
1689
- toolName,
1690
- input,
1691
- output,
1692
- structuredContent,
1693
- sizing,
1694
- displayMode
1695
- });
1696
- if (!withShell) {
1697
- const html3 = `${dataScript}
1698
- ${content}`;
1699
- return {
1700
- html: html3,
1701
- hash: simpleHash(html3),
1702
- size: Buffer.byteLength(html3, "utf-8")
1703
- };
1704
- }
1705
- if (customShell) {
1706
- return buildCustomShell(content, customShell, {
1707
- csp,
1708
- toolName,
1709
- input,
1710
- output,
1711
- structuredContent,
1712
- includeBridge,
1713
- title,
1714
- sizing,
1715
- displayMode,
1716
- dataInjection
1717
- });
1718
- }
1719
- const headParts = [
1720
- '<meta charset="UTF-8">',
1721
- '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
1722
- ];
1723
- if (title) {
1724
- headParts.push(`<title>${escapeHtmlForTag(title)}</title>`);
1725
- }
1726
- headParts.push(buildCSPMetaTag(csp));
1727
- headParts.push(dataScript);
1728
- const sizingStyle = buildSizingStyleTag(sizing);
1729
- if (sizingStyle) {
1730
- headParts.push(sizingStyle);
1731
- }
1732
- if (includeBridge) {
1733
- const bridgeScript = generateBridgeIIFE({ minify: true });
1734
- headParts.push(`<script>${bridgeScript}</script>`);
1735
- }
1736
- const html2 = `<!DOCTYPE html>
1199
+ </script>`}function buildCustomDataInjectionScript(descriptor){if(descriptor.script!==void 0){return descriptor.script}if(descriptor.globalKey!==void 0){return`<script>window[${safeJsonForScript(descriptor.globalKey)}] = ${safeJsonForScript(descriptor.value??null)};</script>`}return""}var _uniqueIdCounter=0;function createTemplateHelpers(){return{escapeHtml:str=>escapeHtml(str),formatDate:(date,format)=>{const d=date instanceof Date?date:new Date(date);if(isNaN(d.getTime()))return String(date);if(format==="iso")return d.toISOString();if(format==="date")return d.toLocaleDateString();if(format==="time")return d.toLocaleTimeString();return d.toLocaleString()},formatCurrency:(amount,currency="USD")=>{return new Intl.NumberFormat("en-US",{style:"currency",currency}).format(amount)},uniqueId:(prefix="mcp")=>{return`${prefix}-${++_uniqueIdCounter}`},jsonEmbed:data=>safeJsonForScript(data),html,trustedHtml}}function sanitizeCssValue(value){return value.replace(/[<>{};]/g,"").trim()}function toCssLength(value){return typeof value==="number"?`${value}px`:sanitizeCssValue(value)}function buildSizingStyleTag(sizing){if(!hasSizing(sizing))return"";const hasCssSizing=sizing.preferredHeight!==void 0||sizing.minHeight!==void 0||sizing.maxHeight!==void 0||sizing.aspectRatio!==void 0;if(!hasCssSizing)return"";const rootRules=[];const docRules=["margin: 0;"];if(sizing.preferredHeight!==void 0){const h=toCssLength(sizing.preferredHeight);docRules.push(`height: ${h};`);rootRules.push(`min-height: ${h};`)}if(sizing.minHeight!==void 0){const mh=toCssLength(sizing.minHeight);docRules.push(`min-height: ${mh};`);rootRules.push(`min-height: ${mh};`)}if(sizing.maxHeight!==void 0){const mx=toCssLength(sizing.maxHeight);docRules.push(`max-height: ${mx};`);rootRules.push(`max-height: ${mx};`)}if(sizing.aspectRatio!==void 0){const ar=typeof sizing.aspectRatio==="number"?String(sizing.aspectRatio):sanitizeCssValue(sizing.aspectRatio);if(ar)rootRules.push(`aspect-ratio: ${ar};`)}const parts=[`html, body { ${docRules.join(" ")} }`];if(rootRules.length>0){parts.push(`#root { ${rootRules.join(" ")} }`)}return`<style>${parts.join("\n")}</style>`}function resolveDataInjectionScript(args){if(args.dataInjection){return buildCustomDataInjectionScript(args.dataInjection)}return buildDataInjectionScript({toolName:args.toolName,input:args.input,output:args.output,structuredContent:args.structuredContent,sizing:args.sizing,displayMode:args.displayMode})}function buildShell(content,config){const{toolName,csp,withShell=true,input,output,structuredContent,includeBridge=true,title,sizing,displayMode}=config;const{customShell,dataInjection}=config;const dataScript=resolveDataInjectionScript({dataInjection,toolName,input,output,structuredContent,sizing,displayMode});if(!withShell){const html3=`${dataScript}
1200
+ ${content}`;return{html:html3,hash:simpleHash(html3),size:Buffer.byteLength(html3,"utf-8")}}if(customShell){return buildCustomShell(content,customShell,{csp,toolName,input,output,structuredContent,includeBridge,title,sizing,displayMode,dataInjection})}const headParts=['<meta charset="UTF-8">','<meta name="viewport" content="width=device-width, initial-scale=1.0">'];if(title){headParts.push(`<title>${escapeHtmlForTag(title)}</title>`)}headParts.push(buildCSPMetaTag(csp));headParts.push(dataScript);const sizingStyle=buildSizingStyleTag(sizing);if(sizingStyle){headParts.push(sizingStyle)}if(includeBridge){const bridgeScript=generateBridgeIIFE({minify:true});headParts.push(`<script>${bridgeScript}</script>`)}const html2=`<!DOCTYPE html>
1737
1201
  <html lang="en">
1738
1202
  <head>
1739
- ${headParts.map((p) => ` ${p}`).join("\n")}
1203
+ ${headParts.map(p=>` ${p}`).join("\n")}
1740
1204
  </head>
1741
1205
  <body>
1742
1206
  ${content}
1743
1207
  </body>
1744
- </html>`;
1745
- return {
1746
- html: html2,
1747
- hash: simpleHash(html2),
1748
- size: Buffer.byteLength(html2, "utf-8")
1749
- };
1750
- }
1751
- function buildCustomShell(content, customShell, ctx) {
1752
- let template;
1753
- if (typeof customShell === "string") {
1754
- const validation = validateShellTemplate(customShell);
1755
- if (!validation.valid) {
1756
- throw new Error(
1757
- `Custom shell template is missing required placeholder(s): ${validation.missingRequired.map((n) => `{{${n}}}`).join(", ")}`
1758
- );
1759
- }
1760
- template = customShell;
1761
- } else {
1762
- template = customShell.template;
1763
- }
1764
- const cspTag = buildCSPMetaTag(ctx.csp);
1765
- const dataScript = resolveDataInjectionScript({
1766
- dataInjection: ctx.dataInjection,
1767
- toolName: ctx.toolName,
1768
- input: ctx.input,
1769
- output: ctx.output,
1770
- structuredContent: ctx.structuredContent,
1771
- sizing: ctx.sizing,
1772
- displayMode: ctx.displayMode
1773
- });
1774
- const sizingStyle = buildSizingStyleTag(ctx.sizing);
1775
- const dataWithSizing = sizingStyle ? `${dataScript}
1776
- ${sizingStyle}` : dataScript;
1777
- let bridgeHtml = "";
1778
- if (ctx.includeBridge) {
1779
- const bridgeScript = generateBridgeIIFE({ minify: true });
1780
- bridgeHtml = `<script>${bridgeScript}</script>`;
1781
- }
1782
- const html2 = applyShellTemplate(template, {
1783
- csp: cspTag,
1784
- data: dataWithSizing,
1785
- bridge: bridgeHtml,
1786
- content,
1787
- title: ctx.title ? escapeHtmlForTag(ctx.title) : ""
1788
- });
1789
- return {
1790
- html: html2,
1791
- hash: simpleHash(html2),
1792
- size: Buffer.byteLength(html2, "utf-8")
1793
- };
1794
- }
1795
- function simpleHash(str) {
1796
- let hash = 0;
1797
- for (let i = 0; i < str.length; i++) {
1798
- const char = str.charCodeAt(i);
1799
- hash = (hash << 5) - hash + char | 0;
1800
- }
1801
- return Math.abs(hash).toString(16).padStart(8, "0");
1802
- }
1803
- function escapeHtmlForTag(str) {
1804
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1805
- }
1806
-
1807
- // libs/uipack/src/shell/custom-shell-resolver.ts
1808
- var DEFAULT_TIMEOUT_MS = 1e4;
1809
- var templateCache = /* @__PURE__ */ new Map();
1810
- async function resolveShellTemplate(source, options) {
1811
- if (isInlineShellSource(source)) {
1812
- return resolveInline(source.inline);
1813
- }
1814
- if (isUrlShellSource(source)) {
1815
- const cacheKey = `url:${source.url}`;
1816
- if (!options?.noCache) {
1817
- const cached = templateCache.get(cacheKey);
1818
- if (cached) return cached;
1819
- }
1820
- const template = await fetchWithTimeout(source.url, source.timeout ?? DEFAULT_TIMEOUT_MS);
1821
- const resolved = buildResolved(template, "url");
1822
- if (!options?.noCache) {
1823
- templateCache.set(cacheKey, resolved);
1824
- }
1825
- return resolved;
1826
- }
1827
- if (isNpmShellSource(source)) {
1828
- const specifier = source.version ? `${source.npm}@${source.version}` : source.npm;
1829
- const cacheKey = `npm:${specifier}`;
1830
- if (!options?.noCache) {
1831
- const cached = templateCache.get(cacheKey);
1832
- if (cached) return cached;
1833
- }
1834
- const template = await resolveNpmTemplate(source, specifier, options?.resolver);
1835
- const resolved = buildResolved(template, "npm");
1836
- if (!options?.noCache) {
1837
- templateCache.set(cacheKey, resolved);
1838
- }
1839
- return resolved;
1840
- }
1841
- throw new Error('Invalid custom shell source: must have "inline", "url", or "npm" property');
1842
- }
1843
- function clearShellTemplateCache() {
1844
- templateCache.clear();
1845
- }
1846
- function resolveInline(template) {
1847
- return buildResolved(template, "inline");
1848
- }
1849
- function buildResolved(template, sourceType) {
1850
- const validation = validateShellTemplate(template);
1851
- if (!validation.valid) {
1852
- throw new Error(
1853
- `Custom shell template is missing required placeholder(s): ${validation.missingRequired.map((n) => `{{${n}}}`).join(", ")}`
1854
- );
1855
- }
1856
- return { template, sourceType, validation };
1857
- }
1858
- async function fetchWithTimeout(url, timeoutMs) {
1859
- const controller = new AbortController();
1860
- const timer = setTimeout(() => controller.abort(), timeoutMs);
1861
- try {
1862
- const response = await fetch(url, { signal: controller.signal });
1863
- if (!response.ok) {
1864
- throw new Error(`Failed to fetch shell template from ${url}: HTTP ${response.status}`);
1865
- }
1866
- return await response.text();
1867
- } catch (err) {
1868
- if (err instanceof Error && err.name === "AbortError") {
1869
- throw new Error(`Shell template fetch timed out after ${timeoutMs}ms: ${url}`);
1870
- }
1871
- throw err;
1872
- } finally {
1873
- clearTimeout(timer);
1874
- }
1875
- }
1876
- async function resolveNpmTemplate(source, specifier, resolver) {
1877
- const cdnUrl = resolveNpmToCdnUrl(specifier, resolver);
1878
- const moduleText = await fetchWithTimeout(cdnUrl, DEFAULT_TIMEOUT_MS);
1879
- return extractTemplateFromModule(moduleText, source.exportName);
1880
- }
1881
- function resolveNpmToCdnUrl(specifier, resolver) {
1882
- if (resolver) {
1883
- const resolved = resolver.resolve(specifier);
1884
- if (resolved) {
1885
- return resolved.value;
1886
- }
1887
- }
1888
- return `https://esm.sh/${specifier}`;
1889
- }
1890
- function extractTemplateFromModule(moduleText, exportName) {
1891
- if (exportName && exportName !== "default") {
1892
- const namedPattern = new RegExp(
1893
- `export\\s+(?:const|let|var)\\s+${escapeRegExp(exportName)}\\s*=\\s*\`([\\s\\S]*?)\``
1894
- );
1895
- const namedMatch = moduleText.match(namedPattern);
1896
- if (namedMatch) {
1897
- return namedMatch[1];
1898
- }
1899
- throw new Error(
1900
- `Could not extract named export "${exportName}" from npm shell package. The package must export a template literal string.`
1901
- );
1902
- }
1903
- const defaultPattern = /export\s+default\s+`([\s\S]*?)`/;
1904
- const defaultMatch = moduleText.match(defaultPattern);
1905
- if (defaultMatch) {
1906
- return defaultMatch[1];
1907
- }
1908
- throw new Error(
1909
- "Could not extract default export from npm shell package. The package must export a template literal string (e.g., export default `<html>...</html>`)."
1910
- );
1911
- }
1912
- function escapeRegExp(str) {
1913
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1914
- }
1915
- export {
1916
- DEFAULT_CDN_DOMAINS,
1917
- DEFAULT_CSP_DIRECTIVES,
1918
- OPTIONAL_PLACEHOLDERS,
1919
- REQUIRED_PLACEHOLDERS,
1920
- RESTRICTIVE_CSP_DIRECTIVES,
1921
- SHELL_PLACEHOLDERS,
1922
- SHELL_PLACEHOLDER_NAMES,
1923
- applyShellTemplate,
1924
- buildCSPDirectives,
1925
- buildCSPMetaTag,
1926
- buildCustomDataInjectionScript,
1927
- buildDataInjectionScript,
1928
- buildShell,
1929
- buildSizingStyleTag,
1930
- clearShellTemplateCache,
1931
- createTemplateHelpers,
1932
- hasSizing,
1933
- html,
1934
- isInlineShellSource,
1935
- isNpmShellSource,
1936
- isTrustedHtml,
1937
- isUrlShellSource,
1938
- resolveShellTemplate,
1939
- sanitizeCSPDomains,
1940
- trustedHtml,
1941
- validateCSPDomain,
1942
- validateShellTemplate
1943
- };
1208
+ </html>`;return{html:html2,hash:simpleHash(html2),size:Buffer.byteLength(html2,"utf-8")}}function buildCustomShell(content,customShell,ctx){let template;if(typeof customShell==="string"){const validation=validateShellTemplate(customShell);if(!validation.valid){throw new Error(`Custom shell template is missing required placeholder(s): ${validation.missingRequired.map(n=>`{{${n}}}`).join(", ")}`)}template=customShell}else{template=customShell.template}const cspTag=buildCSPMetaTag(ctx.csp);const dataScript=resolveDataInjectionScript({dataInjection:ctx.dataInjection,toolName:ctx.toolName,input:ctx.input,output:ctx.output,structuredContent:ctx.structuredContent,sizing:ctx.sizing,displayMode:ctx.displayMode});const sizingStyle=buildSizingStyleTag(ctx.sizing);const dataWithSizing=sizingStyle?`${dataScript}
1209
+ ${sizingStyle}`:dataScript;let bridgeHtml="";if(ctx.includeBridge){const bridgeScript=generateBridgeIIFE({minify:true});bridgeHtml=`<script>${bridgeScript}</script>`}const html2=applyShellTemplate(template,{csp:cspTag,data:dataWithSizing,bridge:bridgeHtml,content,title:ctx.title?escapeHtmlForTag(ctx.title):""});return{html:html2,hash:simpleHash(html2),size:Buffer.byteLength(html2,"utf-8")}}function simpleHash(str){let hash=0;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);hash=(hash<<5)-hash+char|0}return Math.abs(hash).toString(16).padStart(8,"0")}function escapeHtmlForTag(str){return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var DEFAULT_TIMEOUT_MS=1e4;var templateCache=new Map;async function resolveShellTemplate(source,options){if(isInlineShellSource(source)){return resolveInline(source.inline)}if(isUrlShellSource(source)){const cacheKey=`url:${source.url}`;if(!options?.noCache){const cached=templateCache.get(cacheKey);if(cached)return cached}const template=await fetchWithTimeout(source.url,source.timeout??DEFAULT_TIMEOUT_MS);const resolved=buildResolved(template,"url");if(!options?.noCache){templateCache.set(cacheKey,resolved)}return resolved}if(isNpmShellSource(source)){const specifier=source.version?`${source.npm}@${source.version}`:source.npm;const cacheKey=`npm:${specifier}`;if(!options?.noCache){const cached=templateCache.get(cacheKey);if(cached)return cached}const template=await resolveNpmTemplate(source,specifier,options?.resolver);const resolved=buildResolved(template,"npm");if(!options?.noCache){templateCache.set(cacheKey,resolved)}return resolved}throw new Error('Invalid custom shell source: must have "inline", "url", or "npm" property')}function clearShellTemplateCache(){templateCache.clear()}function resolveInline(template){return buildResolved(template,"inline")}function buildResolved(template,sourceType){const validation=validateShellTemplate(template);if(!validation.valid){throw new Error(`Custom shell template is missing required placeholder(s): ${validation.missingRequired.map(n=>`{{${n}}}`).join(", ")}`)}return{template,sourceType,validation}}async function fetchWithTimeout(url,timeoutMs){const controller=new AbortController;const timer=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(url,{signal:controller.signal});if(!response.ok){throw new Error(`Failed to fetch shell template from ${url}: HTTP ${response.status}`)}return await response.text()}catch(err){if(err instanceof Error&&err.name==="AbortError"){throw new Error(`Shell template fetch timed out after ${timeoutMs}ms: ${url}`)}throw err}finally{clearTimeout(timer)}}async function resolveNpmTemplate(source,specifier,resolver){const cdnUrl=resolveNpmToCdnUrl(specifier,resolver);const moduleText=await fetchWithTimeout(cdnUrl,DEFAULT_TIMEOUT_MS);return extractTemplateFromModule(moduleText,source.exportName)}function resolveNpmToCdnUrl(specifier,resolver){if(resolver){const resolved=resolver.resolve(specifier);if(resolved){return resolved.value}}return`https://esm.sh/${specifier}`}function extractTemplateFromModule(moduleText,exportName){if(exportName&&exportName!=="default"){const namedPattern=new RegExp(`export\\s+(?:const|let|var)\\s+${escapeRegExp(exportName)}\\s*=\\s*\`([\\s\\S]*?)\``);const namedMatch=moduleText.match(namedPattern);if(namedMatch){return namedMatch[1]}throw new Error(`Could not extract named export "${exportName}" from npm shell package. The package must export a template literal string.`)}const defaultPattern=/export\s+default\s+`([\s\S]*?)`/;const defaultMatch=moduleText.match(defaultPattern);if(defaultMatch){return defaultMatch[1]}throw new Error("Could not extract default export from npm shell package. The package must export a template literal string (e.g., export default `<html>...</html>`).")}function escapeRegExp(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export{DEFAULT_CDN_DOMAINS,DEFAULT_CSP_DIRECTIVES,OPTIONAL_PLACEHOLDERS,REQUIRED_PLACEHOLDERS,RESTRICTIVE_CSP_DIRECTIVES,SHELL_PLACEHOLDERS,SHELL_PLACEHOLDER_NAMES,applyShellTemplate,buildCSPDirectives,buildCSPMetaTag,buildCustomDataInjectionScript,buildDataInjectionScript,buildShell,buildSizingStyleTag,clearShellTemplateCache,createTemplateHelpers,hasSizing,html,isInlineShellSource,isNpmShellSource,isTrustedHtml,isUrlShellSource,resolveShellTemplate,sanitizeCSPDomains,trustedHtml,validateCSPDomain,validateShellTemplate};