@frontmcp/uipack 0.12.1 → 1.0.0-beta.1

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 (298) hide show
  1. package/CLAUDE.md +56 -154
  2. package/README.md +367 -62
  3. package/adapters/base-template.d.ts +30 -0
  4. package/adapters/base-template.d.ts.map +1 -0
  5. package/adapters/cdn-info.d.ts +34 -0
  6. package/adapters/cdn-info.d.ts.map +1 -0
  7. package/adapters/constants.d.ts +18 -0
  8. package/adapters/constants.d.ts.map +1 -0
  9. package/adapters/content-detector.d.ts +19 -0
  10. package/adapters/content-detector.d.ts.map +1 -0
  11. package/adapters/content-renderers.d.ts +27 -0
  12. package/adapters/content-renderers.d.ts.map +1 -0
  13. package/adapters/index.d.ts +14 -7
  14. package/adapters/index.d.ts.map +1 -1
  15. package/adapters/index.js +2343 -426
  16. package/adapters/render-failure.d.ts +18 -0
  17. package/adapters/render-failure.d.ts.map +1 -0
  18. package/adapters/response-builder.d.ts +34 -104
  19. package/adapters/response-builder.d.ts.map +1 -1
  20. package/adapters/serving-mode.d.ts +28 -91
  21. package/adapters/serving-mode.d.ts.map +1 -1
  22. package/adapters/template-renderer.d.ts +50 -0
  23. package/adapters/template-renderer.d.ts.map +1 -0
  24. package/adapters/type-detector.d.ts +18 -0
  25. package/adapters/type-detector.d.ts.map +1 -0
  26. package/bridge-runtime/index.js +1 -1
  27. package/component/index.d.ts +14 -0
  28. package/component/index.d.ts.map +1 -0
  29. package/component/index.js +2043 -0
  30. package/component/loader.d.ts +36 -0
  31. package/component/loader.d.ts.map +1 -0
  32. package/component/renderer.d.ts +30 -0
  33. package/component/renderer.d.ts.map +1 -0
  34. package/component/transpiler.d.ts +49 -0
  35. package/component/transpiler.d.ts.map +1 -0
  36. package/component/types.d.ts +82 -0
  37. package/component/types.d.ts.map +1 -0
  38. package/esm/adapters/index.mjs +2337 -422
  39. package/esm/bridge-runtime/index.mjs +1 -1
  40. package/esm/component/index.mjs +2013 -0
  41. package/esm/index.mjs +3446 -13935
  42. package/esm/package.json +3 -12
  43. package/esm/resolver/index.mjs +661 -0
  44. package/esm/shell/index.mjs +1406 -0
  45. package/esm/types/index.mjs +11 -11
  46. package/esm/utils/index.mjs +53 -8
  47. package/index.d.ts +12 -40
  48. package/index.d.ts.map +1 -1
  49. package/index.js +3579 -14218
  50. package/package.json +3 -12
  51. package/resolver/cdn-registry.d.ts +39 -0
  52. package/resolver/cdn-registry.d.ts.map +1 -0
  53. package/resolver/esm-sh.resolver.d.ts +54 -0
  54. package/resolver/esm-sh.resolver.d.ts.map +1 -0
  55. package/resolver/import-map.d.ts +47 -0
  56. package/resolver/import-map.d.ts.map +1 -0
  57. package/resolver/import-parser.d.ts +28 -0
  58. package/resolver/import-parser.d.ts.map +1 -0
  59. package/resolver/import-rewriter.d.ts +29 -0
  60. package/resolver/import-rewriter.d.ts.map +1 -0
  61. package/resolver/index.d.ts +15 -0
  62. package/resolver/index.d.ts.map +1 -0
  63. package/resolver/index.js +708 -0
  64. package/resolver/types.d.ts +191 -0
  65. package/resolver/types.d.ts.map +1 -0
  66. package/shell/builder.d.ts +31 -0
  67. package/shell/builder.d.ts.map +1 -0
  68. package/shell/csp.d.ts +37 -0
  69. package/shell/csp.d.ts.map +1 -0
  70. package/shell/custom-shell-applier.d.ts +33 -0
  71. package/shell/custom-shell-applier.d.ts.map +1 -0
  72. package/shell/custom-shell-resolver.d.ts +47 -0
  73. package/shell/custom-shell-resolver.d.ts.map +1 -0
  74. package/shell/custom-shell-types.d.ts +75 -0
  75. package/shell/custom-shell-types.d.ts.map +1 -0
  76. package/shell/custom-shell-validator.d.ts +26 -0
  77. package/shell/custom-shell-validator.d.ts.map +1 -0
  78. package/shell/data-injector.d.ts +40 -0
  79. package/shell/data-injector.d.ts.map +1 -0
  80. package/shell/index.d.ts +19 -0
  81. package/shell/index.d.ts.map +1 -0
  82. package/shell/index.js +1453 -0
  83. package/shell/types.d.ts +54 -0
  84. package/shell/types.d.ts.map +1 -0
  85. package/types/index.d.ts +1 -3
  86. package/types/index.d.ts.map +1 -1
  87. package/types/index.js +11 -11
  88. package/types/ui-config.d.ts +50 -11
  89. package/types/ui-config.d.ts.map +1 -1
  90. package/types/ui-runtime.d.ts +8 -82
  91. package/types/ui-runtime.d.ts.map +1 -1
  92. package/utils/index.d.ts +9 -3
  93. package/utils/index.d.ts.map +1 -1
  94. package/utils/index.js +59 -7
  95. package/adapters/platform-meta.constants.d.ts +0 -26
  96. package/adapters/platform-meta.constants.d.ts.map +0 -1
  97. package/adapters/platform-meta.d.ts +0 -234
  98. package/adapters/platform-meta.d.ts.map +0 -1
  99. package/base-template/bridge.d.ts +0 -90
  100. package/base-template/bridge.d.ts.map +0 -1
  101. package/base-template/default-base-template.d.ts +0 -91
  102. package/base-template/default-base-template.d.ts.map +0 -1
  103. package/base-template/index.d.ts +0 -15
  104. package/base-template/index.d.ts.map +0 -1
  105. package/base-template/index.js +0 -1393
  106. package/base-template/polyfills.d.ts +0 -31
  107. package/base-template/polyfills.d.ts.map +0 -1
  108. package/base-template/theme-styles.d.ts +0 -74
  109. package/base-template/theme-styles.d.ts.map +0 -1
  110. package/build/builders/base-builder.d.ts +0 -124
  111. package/build/builders/base-builder.d.ts.map +0 -1
  112. package/build/builders/esbuild-config.d.ts +0 -94
  113. package/build/builders/esbuild-config.d.ts.map +0 -1
  114. package/build/builders/hybrid-builder.d.ts +0 -93
  115. package/build/builders/hybrid-builder.d.ts.map +0 -1
  116. package/build/builders/index.d.ts +0 -17
  117. package/build/builders/index.d.ts.map +0 -1
  118. package/build/builders/inline-builder.d.ts +0 -83
  119. package/build/builders/inline-builder.d.ts.map +0 -1
  120. package/build/builders/static-builder.d.ts +0 -78
  121. package/build/builders/static-builder.d.ts.map +0 -1
  122. package/build/builders/types.d.ts +0 -341
  123. package/build/builders/types.d.ts.map +0 -1
  124. package/build/cdn-resources.d.ts +0 -244
  125. package/build/cdn-resources.d.ts.map +0 -1
  126. package/build/hybrid-data.d.ts +0 -127
  127. package/build/hybrid-data.d.ts.map +0 -1
  128. package/build/index.d.ts +0 -299
  129. package/build/index.d.ts.map +0 -1
  130. package/build/index.js +0 -8699
  131. package/build/ui-components-browser.d.ts +0 -64
  132. package/build/ui-components-browser.d.ts.map +0 -1
  133. package/build/widget-manifest.d.ts +0 -362
  134. package/build/widget-manifest.d.ts.map +0 -1
  135. package/bundler/cache.d.ts +0 -173
  136. package/bundler/cache.d.ts.map +0 -1
  137. package/bundler/file-cache/component-builder.d.ts +0 -167
  138. package/bundler/file-cache/component-builder.d.ts.map +0 -1
  139. package/bundler/file-cache/hash-calculator.d.ts +0 -155
  140. package/bundler/file-cache/hash-calculator.d.ts.map +0 -1
  141. package/bundler/file-cache/index.d.ts +0 -12
  142. package/bundler/file-cache/index.d.ts.map +0 -1
  143. package/bundler/file-cache/storage/filesystem.d.ts +0 -149
  144. package/bundler/file-cache/storage/filesystem.d.ts.map +0 -1
  145. package/bundler/file-cache/storage/index.d.ts +0 -11
  146. package/bundler/file-cache/storage/index.d.ts.map +0 -1
  147. package/bundler/file-cache/storage/interface.d.ts +0 -152
  148. package/bundler/file-cache/storage/interface.d.ts.map +0 -1
  149. package/bundler/file-cache/storage/redis.d.ts +0 -139
  150. package/bundler/file-cache/storage/redis.d.ts.map +0 -1
  151. package/bundler/index.d.ts +0 -35
  152. package/bundler/index.d.ts.map +0 -1
  153. package/bundler/index.js +0 -2953
  154. package/bundler/sandbox/enclave-adapter.d.ts +0 -121
  155. package/bundler/sandbox/enclave-adapter.d.ts.map +0 -1
  156. package/bundler/sandbox/executor.d.ts +0 -14
  157. package/bundler/sandbox/executor.d.ts.map +0 -1
  158. package/bundler/sandbox/policy.d.ts +0 -62
  159. package/bundler/sandbox/policy.d.ts.map +0 -1
  160. package/bundler/types.d.ts +0 -702
  161. package/bundler/types.d.ts.map +0 -1
  162. package/dependency/cdn-registry.d.ts +0 -98
  163. package/dependency/cdn-registry.d.ts.map +0 -1
  164. package/dependency/import-map.d.ts +0 -186
  165. package/dependency/import-map.d.ts.map +0 -1
  166. package/dependency/import-parser.d.ts +0 -82
  167. package/dependency/import-parser.d.ts.map +0 -1
  168. package/dependency/index.d.ts +0 -17
  169. package/dependency/index.d.ts.map +0 -1
  170. package/dependency/index.js +0 -3180
  171. package/dependency/resolver.d.ts +0 -164
  172. package/dependency/resolver.d.ts.map +0 -1
  173. package/dependency/schemas.d.ts +0 -486
  174. package/dependency/schemas.d.ts.map +0 -1
  175. package/dependency/template-loader.d.ts +0 -204
  176. package/dependency/template-loader.d.ts.map +0 -1
  177. package/dependency/template-processor.d.ts +0 -118
  178. package/dependency/template-processor.d.ts.map +0 -1
  179. package/dependency/types.d.ts +0 -739
  180. package/dependency/types.d.ts.map +0 -1
  181. package/esm/base-template/index.mjs +0 -1359
  182. package/esm/build/index.mjs +0 -8601
  183. package/esm/bundler/index.mjs +0 -2895
  184. package/esm/dependency/index.mjs +0 -3068
  185. package/esm/handlebars/index.mjs +0 -587
  186. package/esm/registry/index.mjs +0 -6305
  187. package/esm/renderers/index.mjs +0 -1557
  188. package/esm/runtime/index.mjs +0 -5361
  189. package/esm/styles/index.mjs +0 -171
  190. package/esm/theme/index.mjs +0 -756
  191. package/esm/tool-template/index.mjs +0 -3652
  192. package/esm/validation/index.mjs +0 -542
  193. package/handlebars/expression-extractor.d.ts +0 -147
  194. package/handlebars/expression-extractor.d.ts.map +0 -1
  195. package/handlebars/helpers.d.ts +0 -339
  196. package/handlebars/helpers.d.ts.map +0 -1
  197. package/handlebars/index.d.ts +0 -195
  198. package/handlebars/index.d.ts.map +0 -1
  199. package/handlebars/index.js +0 -659
  200. package/preview/claude-preview.d.ts +0 -67
  201. package/preview/claude-preview.d.ts.map +0 -1
  202. package/preview/generic-preview.d.ts +0 -66
  203. package/preview/generic-preview.d.ts.map +0 -1
  204. package/preview/index.d.ts +0 -36
  205. package/preview/index.d.ts.map +0 -1
  206. package/preview/openai-preview.d.ts +0 -70
  207. package/preview/openai-preview.d.ts.map +0 -1
  208. package/preview/types.d.ts +0 -199
  209. package/preview/types.d.ts.map +0 -1
  210. package/registry/index.d.ts +0 -46
  211. package/registry/index.d.ts.map +0 -1
  212. package/registry/index.js +0 -6342
  213. package/registry/render-template.d.ts +0 -91
  214. package/registry/render-template.d.ts.map +0 -1
  215. package/registry/tool-ui.registry.d.ts +0 -294
  216. package/registry/tool-ui.registry.d.ts.map +0 -1
  217. package/registry/uri-utils.d.ts +0 -56
  218. package/registry/uri-utils.d.ts.map +0 -1
  219. package/renderers/cache.d.ts +0 -145
  220. package/renderers/cache.d.ts.map +0 -1
  221. package/renderers/html.renderer.d.ts +0 -123
  222. package/renderers/html.renderer.d.ts.map +0 -1
  223. package/renderers/index.d.ts +0 -36
  224. package/renderers/index.d.ts.map +0 -1
  225. package/renderers/index.js +0 -1603
  226. package/renderers/mdx-client.renderer.d.ts +0 -124
  227. package/renderers/mdx-client.renderer.d.ts.map +0 -1
  228. package/renderers/registry.d.ts +0 -133
  229. package/renderers/registry.d.ts.map +0 -1
  230. package/renderers/types.d.ts +0 -343
  231. package/renderers/types.d.ts.map +0 -1
  232. package/renderers/utils/detect.d.ts +0 -107
  233. package/renderers/utils/detect.d.ts.map +0 -1
  234. package/renderers/utils/hash.d.ts +0 -40
  235. package/renderers/utils/hash.d.ts.map +0 -1
  236. package/renderers/utils/index.d.ts +0 -9
  237. package/renderers/utils/index.d.ts.map +0 -1
  238. package/renderers/utils/transpiler.d.ts +0 -70
  239. package/renderers/utils/transpiler.d.ts.map +0 -1
  240. package/runtime/adapters/html.adapter.d.ts +0 -59
  241. package/runtime/adapters/html.adapter.d.ts.map +0 -1
  242. package/runtime/adapters/index.d.ts +0 -26
  243. package/runtime/adapters/index.d.ts.map +0 -1
  244. package/runtime/adapters/mdx.adapter.d.ts +0 -73
  245. package/runtime/adapters/mdx.adapter.d.ts.map +0 -1
  246. package/runtime/adapters/types.d.ts +0 -95
  247. package/runtime/adapters/types.d.ts.map +0 -1
  248. package/runtime/csp.d.ts +0 -48
  249. package/runtime/csp.d.ts.map +0 -1
  250. package/runtime/index.d.ts +0 -17
  251. package/runtime/index.d.ts.map +0 -1
  252. package/runtime/index.js +0 -5432
  253. package/runtime/mcp-bridge.d.ts +0 -101
  254. package/runtime/mcp-bridge.d.ts.map +0 -1
  255. package/runtime/renderer-runtime.d.ts +0 -133
  256. package/runtime/renderer-runtime.d.ts.map +0 -1
  257. package/runtime/sanitizer.d.ts +0 -180
  258. package/runtime/sanitizer.d.ts.map +0 -1
  259. package/runtime/types.d.ts +0 -415
  260. package/runtime/types.d.ts.map +0 -1
  261. package/runtime/wrapper.d.ts +0 -421
  262. package/runtime/wrapper.d.ts.map +0 -1
  263. package/styles/index.d.ts +0 -8
  264. package/styles/index.d.ts.map +0 -1
  265. package/styles/index.js +0 -222
  266. package/styles/variants.d.ts +0 -51
  267. package/styles/variants.d.ts.map +0 -1
  268. package/theme/cdn.d.ts +0 -195
  269. package/theme/cdn.d.ts.map +0 -1
  270. package/theme/css-to-theme.d.ts +0 -64
  271. package/theme/css-to-theme.d.ts.map +0 -1
  272. package/theme/index.d.ts +0 -19
  273. package/theme/index.d.ts.map +0 -1
  274. package/theme/index.js +0 -814
  275. package/theme/platforms.d.ts +0 -102
  276. package/theme/platforms.d.ts.map +0 -1
  277. package/theme/presets/github-openai.d.ts +0 -50
  278. package/theme/presets/github-openai.d.ts.map +0 -1
  279. package/theme/presets/index.d.ts +0 -11
  280. package/theme/presets/index.d.ts.map +0 -1
  281. package/theme/theme.d.ts +0 -396
  282. package/theme/theme.d.ts.map +0 -1
  283. package/tool-template/builder.d.ts +0 -213
  284. package/tool-template/builder.d.ts.map +0 -1
  285. package/tool-template/index.d.ts +0 -16
  286. package/tool-template/index.d.ts.map +0 -1
  287. package/tool-template/index.js +0 -3690
  288. package/validation/error-box.d.ts +0 -56
  289. package/validation/error-box.d.ts.map +0 -1
  290. package/validation/index.d.ts +0 -13
  291. package/validation/index.d.ts.map +0 -1
  292. package/validation/index.js +0 -576
  293. package/validation/schema-paths.d.ts +0 -118
  294. package/validation/schema-paths.d.ts.map +0 -1
  295. package/validation/template-validator.d.ts +0 -143
  296. package/validation/template-validator.d.ts.map +0 -1
  297. package/validation/wrapper.d.ts +0 -97
  298. package/validation/wrapper.d.ts.map +0 -1
@@ -1,3652 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn, res) => function __init() {
4
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
- };
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
-
11
- // libs/uipack/src/utils/index.ts
12
- import {
13
- safeStringify,
14
- escapeHtml,
15
- escapeHtmlAttr,
16
- escapeJsString,
17
- escapeScriptClose,
18
- safeJsonForScript
19
- } from "@frontmcp/utils";
20
- var init_utils = __esm({
21
- "libs/uipack/src/utils/index.ts"() {
22
- "use strict";
23
- }
24
- });
25
-
26
- // libs/uipack/src/handlebars/helpers.ts
27
- function formatDate(date, format) {
28
- if (date === null || date === void 0) {
29
- return "";
30
- }
31
- let dateObj;
32
- if (date instanceof Date) {
33
- dateObj = date;
34
- } else if (typeof date === "string" || typeof date === "number") {
35
- dateObj = new Date(date);
36
- } else {
37
- return String(date);
38
- }
39
- if (isNaN(dateObj.getTime())) {
40
- return String(date);
41
- }
42
- const options = {};
43
- switch (format) {
44
- case "short":
45
- options.dateStyle = "short";
46
- break;
47
- case "medium":
48
- options.dateStyle = "medium";
49
- break;
50
- case "long":
51
- options.dateStyle = "long";
52
- break;
53
- case "full":
54
- options.dateStyle = "full";
55
- break;
56
- case "time":
57
- options.timeStyle = "short";
58
- break;
59
- case "datetime":
60
- options.dateStyle = "medium";
61
- options.timeStyle = "short";
62
- break;
63
- case "iso":
64
- return dateObj.toISOString();
65
- case "relative":
66
- return formatRelativeDate(dateObj);
67
- default:
68
- options.dateStyle = "medium";
69
- }
70
- return new Intl.DateTimeFormat("en-US", options).format(dateObj);
71
- }
72
- function formatRelativeDate(date) {
73
- const now = /* @__PURE__ */ new Date();
74
- const diffMs = now.getTime() - date.getTime();
75
- const diffSecs = Math.floor(diffMs / 1e3);
76
- const diffMins = Math.floor(diffSecs / 60);
77
- const diffHours = Math.floor(diffMins / 60);
78
- const diffDays = Math.floor(diffHours / 24);
79
- if (diffSecs < 60) {
80
- return "just now";
81
- } else if (diffMins < 60) {
82
- return `${diffMins} minute${diffMins === 1 ? "" : "s"} ago`;
83
- } else if (diffHours < 24) {
84
- return `${diffHours} hour${diffHours === 1 ? "" : "s"} ago`;
85
- } else if (diffDays < 7) {
86
- return `${diffDays} day${diffDays === 1 ? "" : "s"} ago`;
87
- } else {
88
- return formatDate(date, "medium");
89
- }
90
- }
91
- function formatCurrency(amount, currency) {
92
- if (amount === null || amount === void 0) {
93
- return "";
94
- }
95
- const num = typeof amount === "number" ? amount : parseFloat(String(amount));
96
- if (isNaN(num)) {
97
- return String(amount);
98
- }
99
- return new Intl.NumberFormat("en-US", {
100
- style: "currency",
101
- currency: typeof currency === "string" ? currency : "USD"
102
- }).format(num);
103
- }
104
- function formatNumber(value, decimals) {
105
- if (value === null || value === void 0) {
106
- return "";
107
- }
108
- const num = typeof value === "number" ? value : parseFloat(String(value));
109
- if (isNaN(num)) {
110
- return String(value);
111
- }
112
- const options = {};
113
- if (typeof decimals === "number") {
114
- options.minimumFractionDigits = decimals;
115
- options.maximumFractionDigits = decimals;
116
- }
117
- return new Intl.NumberFormat("en-US", options).format(num);
118
- }
119
- function jsonEmbed(data) {
120
- const json2 = JSON.stringify(data ?? null);
121
- return json2.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
122
- }
123
- function json(data, pretty) {
124
- return JSON.stringify(data ?? null, null, pretty ? 2 : void 0);
125
- }
126
- function eq(a, b) {
127
- return a === b;
128
- }
129
- function ne(a, b) {
130
- return a !== b;
131
- }
132
- function gt(a, b) {
133
- return Number(a) > Number(b);
134
- }
135
- function gte(a, b) {
136
- return Number(a) >= Number(b);
137
- }
138
- function lt(a, b) {
139
- return Number(a) < Number(b);
140
- }
141
- function lte(a, b) {
142
- return Number(a) <= Number(b);
143
- }
144
- function and(a, b) {
145
- return Boolean(a) && Boolean(b);
146
- }
147
- function or(a, b) {
148
- return Boolean(a) || Boolean(b);
149
- }
150
- function not(value) {
151
- return !value;
152
- }
153
- function first(arr) {
154
- if (!Array.isArray(arr)) return void 0;
155
- return arr[0];
156
- }
157
- function last(arr) {
158
- if (!Array.isArray(arr)) return void 0;
159
- return arr[arr.length - 1];
160
- }
161
- function length(value) {
162
- if (Array.isArray(value)) return value.length;
163
- if (typeof value === "string") return value.length;
164
- return 0;
165
- }
166
- function includes(arr, value) {
167
- if (!Array.isArray(arr)) return false;
168
- return arr.includes(value);
169
- }
170
- function join(arr, separator) {
171
- if (!Array.isArray(arr)) return "";
172
- return arr.join(typeof separator === "string" ? separator : ", ");
173
- }
174
- function uppercase(str) {
175
- return String(str ?? "").toUpperCase();
176
- }
177
- function lowercase(str) {
178
- return String(str ?? "").toLowerCase();
179
- }
180
- function capitalize(str) {
181
- const s = String(str ?? "");
182
- return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
183
- }
184
- function truncate(str, maxLength, suffix) {
185
- const s = String(str ?? "");
186
- const len = typeof maxLength === "number" ? maxLength : 50;
187
- const suf = typeof suffix === "string" ? suffix : "...";
188
- if (s.length <= len) return s;
189
- return s.slice(0, len - suf.length) + suf;
190
- }
191
- function defaultValue(value, defaultValue2) {
192
- return value || defaultValue2;
193
- }
194
- function uniqueId(prefix) {
195
- const id = ++idCounter;
196
- return prefix ? `${prefix}-${id}` : `id-${id}`;
197
- }
198
- function resetUniqueIdCounter() {
199
- idCounter = 0;
200
- }
201
- function classNames(...classes) {
202
- return classes.filter(Boolean).map(String).join(" ");
203
- }
204
- var idCounter, builtinHelpers;
205
- var init_helpers = __esm({
206
- "libs/uipack/src/handlebars/helpers.ts"() {
207
- "use strict";
208
- init_utils();
209
- idCounter = 0;
210
- builtinHelpers = {
211
- // Escaping
212
- escapeHtml,
213
- // Formatting
214
- formatDate,
215
- formatCurrency,
216
- formatNumber,
217
- json,
218
- jsonEmbed,
219
- // Comparison
220
- eq,
221
- ne,
222
- gt,
223
- gte,
224
- lt,
225
- lte,
226
- // Logical
227
- and,
228
- or,
229
- not,
230
- // Array
231
- first,
232
- last,
233
- length,
234
- includes,
235
- join,
236
- // String
237
- uppercase,
238
- lowercase,
239
- capitalize,
240
- truncate,
241
- // Utility
242
- default: defaultValue,
243
- uniqueId,
244
- classNames
245
- };
246
- }
247
- });
248
-
249
- // libs/uipack/src/handlebars/expression-extractor.ts
250
- function extractExpressions(template) {
251
- const expressions = [];
252
- const positionMap = buildPositionMap(template);
253
- let match;
254
- EXPRESSION_REGEX.lastIndex = 0;
255
- while ((match = EXPRESSION_REGEX.exec(template)) !== null) {
256
- const fullExpression = match[0];
257
- const prefix = match[1];
258
- const content = match[2].trim();
259
- const position = positionMap.get(match.index) ?? { line: 1, column: 1 };
260
- let type = "variable";
261
- let helperName;
262
- if (prefix === "/") {
263
- type = "block-close";
264
- helperName = content;
265
- } else if (prefix === "#") {
266
- type = "block";
267
- const parts = content.split(/\s+/);
268
- helperName = parts[0];
269
- } else {
270
- const parts = content.split(/\s+/);
271
- if (parts.length > 1 && !content.startsWith("(")) {
272
- const firstToken = parts[0];
273
- if (!firstToken.includes(".") && !KEYWORDS.has(firstToken)) {
274
- type = "helper";
275
- helperName = firstToken;
276
- }
277
- }
278
- }
279
- const paths = extractPathsFromContent(content);
280
- for (const path of paths) {
281
- expressions.push({
282
- path,
283
- fullExpression,
284
- line: position.line,
285
- column: position.column,
286
- type,
287
- helperName
288
- });
289
- }
290
- if (paths.length === 0 && type === "variable") {
291
- const cleanContent = content.trim();
292
- if (!KEYWORDS.has(cleanContent) && !cleanContent.includes(" ") && !cleanContent.startsWith("(")) {
293
- }
294
- }
295
- }
296
- return expressions;
297
- }
298
- function extractPathsFromContent(content) {
299
- const paths = [];
300
- let match;
301
- const regex = new RegExp(PATH_REGEX.source, "g");
302
- while ((match = regex.exec(content)) !== null) {
303
- paths.push(match[0]);
304
- }
305
- return paths;
306
- }
307
- function buildPositionMap(template) {
308
- const map = /* @__PURE__ */ new Map();
309
- let line = 1;
310
- let column = 1;
311
- for (let i = 0; i < template.length; i++) {
312
- map.set(i, { line, column });
313
- if (template[i] === "\n") {
314
- line++;
315
- column = 1;
316
- } else {
317
- column++;
318
- }
319
- }
320
- return map;
321
- }
322
- function extractVariablePaths(template) {
323
- const expressions = extractExpressions(template);
324
- const paths = new Set(expressions.map((e) => e.path));
325
- return Array.from(paths);
326
- }
327
- function extractOutputPaths(template) {
328
- return extractVariablePaths(template).filter((p) => p.startsWith("output."));
329
- }
330
- function extractInputPaths(template) {
331
- return extractVariablePaths(template).filter((p) => p.startsWith("input."));
332
- }
333
- function extractStructuredContentPaths(template) {
334
- return extractVariablePaths(template).filter((p) => p.startsWith("structuredContent."));
335
- }
336
- function extractAll(template) {
337
- const expressions = extractExpressions(template);
338
- const paths = [...new Set(expressions.map((e) => e.path))];
339
- return {
340
- expressions,
341
- paths,
342
- outputPaths: paths.filter((p) => p.startsWith("output.")),
343
- inputPaths: paths.filter((p) => p.startsWith("input.")),
344
- structuredContentPaths: paths.filter((p) => p.startsWith("structuredContent."))
345
- };
346
- }
347
- function hasVariablePaths(template) {
348
- return extractVariablePaths(template).length > 0;
349
- }
350
- function getExpressionAt(template, line, column) {
351
- const expressions = extractExpressions(template);
352
- return expressions.find((expr) => {
353
- if (expr.line !== line) return false;
354
- const exprEnd = expr.column + expr.fullExpression.length;
355
- return column >= expr.column && column <= exprEnd;
356
- });
357
- }
358
- function normalizePath(path) {
359
- return path.replace(/\.\d+\./g, ".[].").replace(/\.\d+$/g, ".[]").replace(/\[\d+\]/g, ".[]");
360
- }
361
- var EXPRESSION_REGEX, PATH_REGEX, KEYWORDS;
362
- var init_expression_extractor = __esm({
363
- "libs/uipack/src/handlebars/expression-extractor.ts"() {
364
- "use strict";
365
- EXPRESSION_REGEX = /\{\{\{?(?!!)(#|\/)?([^}]+?)\}?\}\}/g;
366
- PATH_REGEX = /\b(output|input|structuredContent)(\.[a-zA-Z_$][a-zA-Z0-9_$]*|\.\[[^\]]+\])+/g;
367
- KEYWORDS = /* @__PURE__ */ new Set(["this", "else", "@index", "@key", "@first", "@last", "@root"]);
368
- }
369
- });
370
-
371
- // libs/uipack/src/handlebars/index.ts
372
- var handlebars_exports = {};
373
- __export(handlebars_exports, {
374
- HandlebarsRenderer: () => HandlebarsRenderer,
375
- and: () => and,
376
- builtinHelpers: () => builtinHelpers,
377
- capitalize: () => capitalize,
378
- classNames: () => classNames,
379
- containsHandlebars: () => containsHandlebars,
380
- createHandlebarsRenderer: () => createHandlebarsRenderer,
381
- defaultValue: () => defaultValue,
382
- eq: () => eq,
383
- escapeHtml: () => escapeHtml,
384
- extractAll: () => extractAll,
385
- extractExpressions: () => extractExpressions,
386
- extractInputPaths: () => extractInputPaths,
387
- extractOutputPaths: () => extractOutputPaths,
388
- extractStructuredContentPaths: () => extractStructuredContentPaths,
389
- extractVariablePaths: () => extractVariablePaths,
390
- first: () => first,
391
- formatCurrency: () => formatCurrency,
392
- formatDate: () => formatDate,
393
- formatNumber: () => formatNumber,
394
- getExpressionAt: () => getExpressionAt,
395
- gt: () => gt,
396
- gte: () => gte,
397
- hasVariablePaths: () => hasVariablePaths,
398
- includes: () => includes,
399
- isHandlebarsAvailable: () => isHandlebarsAvailable,
400
- join: () => join,
401
- json: () => json,
402
- jsonEmbed: () => jsonEmbed,
403
- last: () => last,
404
- length: () => length,
405
- lowercase: () => lowercase,
406
- lt: () => lt,
407
- lte: () => lte,
408
- ne: () => ne,
409
- normalizePath: () => normalizePath,
410
- not: () => not,
411
- or: () => or,
412
- renderTemplate: () => renderTemplate,
413
- resetUniqueIdCounter: () => resetUniqueIdCounter,
414
- truncate: () => truncate,
415
- uniqueId: () => uniqueId,
416
- uppercase: () => uppercase
417
- });
418
- async function loadHandlebars() {
419
- if (Handlebars !== null) {
420
- return Handlebars;
421
- }
422
- try {
423
- Handlebars = await import("handlebars");
424
- return Handlebars;
425
- } catch {
426
- throw new Error("Handlebars is required for template rendering. Install it: npm install handlebars");
427
- }
428
- }
429
- async function isHandlebarsAvailable() {
430
- try {
431
- await loadHandlebars();
432
- return true;
433
- } catch {
434
- return false;
435
- }
436
- }
437
- function createHandlebarsRenderer(options) {
438
- return new HandlebarsRenderer(options);
439
- }
440
- async function renderTemplate(template, context) {
441
- const renderer = createHandlebarsRenderer();
442
- return renderer.render(template, context);
443
- }
444
- function containsHandlebars(template) {
445
- return HandlebarsRenderer.containsHandlebars(template);
446
- }
447
- var Handlebars, HandlebarsRenderer;
448
- var init_handlebars = __esm({
449
- "libs/uipack/src/handlebars/index.ts"() {
450
- "use strict";
451
- init_helpers();
452
- init_helpers();
453
- init_expression_extractor();
454
- Handlebars = null;
455
- HandlebarsRenderer = class {
456
- options;
457
- compiledTemplates = /* @__PURE__ */ new Map();
458
- initialized = false;
459
- hbs = null;
460
- constructor(options = {}) {
461
- this.options = {
462
- strict: false,
463
- autoEscape: true,
464
- ...options
465
- };
466
- }
467
- /**
468
- * Initialize the renderer with Handlebars.
469
- */
470
- async init() {
471
- if (this.initialized) return;
472
- this.hbs = await loadHandlebars();
473
- for (const [name, helper] of Object.entries(builtinHelpers)) {
474
- this.hbs.registerHelper(name, helper);
475
- }
476
- if (this.options.helpers) {
477
- for (const [name, helper] of Object.entries(this.options.helpers)) {
478
- this.hbs.registerHelper(name, helper);
479
- }
480
- }
481
- if (this.options.partials) {
482
- for (const [name, template] of Object.entries(this.options.partials)) {
483
- this.hbs.registerPartial(name, template);
484
- }
485
- }
486
- this.initialized = true;
487
- }
488
- /**
489
- * Render a Handlebars template.
490
- *
491
- * @param template - Template string
492
- * @param context - Render context with input/output
493
- * @returns Rendered HTML string
494
- */
495
- async render(template, context) {
496
- await this.init();
497
- if (!this.hbs) {
498
- throw new Error("Handlebars not initialized");
499
- }
500
- let compiled = this.compiledTemplates.get(template);
501
- if (!compiled) {
502
- compiled = this.hbs.compile(template, {
503
- strict: this.options.strict,
504
- noEscape: !this.options.autoEscape
505
- });
506
- this.compiledTemplates.set(template, compiled);
507
- }
508
- const data = {
509
- input: context.input ?? {},
510
- output: context.output ?? {},
511
- structuredContent: context.structuredContent,
512
- // Also expose at root level for convenience
513
- ...context.input,
514
- ...typeof context.output === "object" && context.output !== null ? context.output : {}
515
- };
516
- try {
517
- return compiled(data);
518
- } catch (error) {
519
- throw new Error(`Template rendering failed: ${error instanceof Error ? error.message : String(error)}`);
520
- }
521
- }
522
- /**
523
- * Render a template synchronously.
524
- *
525
- * Note: Requires Handlebars to be pre-loaded. Use `render()` for async loading.
526
- *
527
- * @param template - Template string
528
- * @param context - Render context
529
- * @returns Rendered HTML string
530
- */
531
- renderSync(template, context) {
532
- if (!this.initialized || !this.hbs) {
533
- throw new Error("HandlebarsRenderer not initialized. Call render() first or use initSync().");
534
- }
535
- let compiled = this.compiledTemplates.get(template);
536
- if (!compiled) {
537
- compiled = this.hbs.compile(template, {
538
- strict: this.options.strict,
539
- noEscape: !this.options.autoEscape
540
- });
541
- this.compiledTemplates.set(template, compiled);
542
- }
543
- const data = {
544
- input: context.input ?? {},
545
- output: context.output ?? {},
546
- structuredContent: context.structuredContent,
547
- ...context.input,
548
- ...typeof context.output === "object" && context.output !== null ? context.output : {}
549
- };
550
- return compiled(data);
551
- }
552
- /**
553
- * Initialize synchronously (for environments where Handlebars is already loaded).
554
- */
555
- initSync(handlebars) {
556
- this.hbs = handlebars;
557
- for (const [name, helper] of Object.entries(builtinHelpers)) {
558
- this.hbs.registerHelper(name, helper);
559
- }
560
- if (this.options.helpers) {
561
- for (const [name, helper] of Object.entries(this.options.helpers)) {
562
- this.hbs.registerHelper(name, helper);
563
- }
564
- }
565
- if (this.options.partials) {
566
- for (const [name, template] of Object.entries(this.options.partials)) {
567
- this.hbs.registerPartial(name, template);
568
- }
569
- }
570
- this.initialized = true;
571
- }
572
- /**
573
- * Register a custom helper.
574
- *
575
- * @param name - Helper name
576
- * @param fn - Helper function
577
- */
578
- registerHelper(name, fn) {
579
- if (this.hbs) {
580
- this.hbs.registerHelper(name, fn);
581
- }
582
- if (!this.options.helpers) {
583
- this.options.helpers = {};
584
- }
585
- this.options.helpers[name] = fn;
586
- }
587
- /**
588
- * Register a partial template.
589
- *
590
- * @param name - Partial name
591
- * @param template - Partial template string
592
- */
593
- registerPartial(name, template) {
594
- if (this.hbs) {
595
- this.hbs.registerPartial(name, template);
596
- }
597
- if (!this.options.partials) {
598
- this.options.partials = {};
599
- }
600
- this.options.partials[name] = template;
601
- }
602
- /**
603
- * Clear compiled template cache.
604
- */
605
- clearCache() {
606
- this.compiledTemplates.clear();
607
- }
608
- /**
609
- * Check if a template string contains Handlebars syntax.
610
- *
611
- * @param template - Template string to check
612
- * @returns true if contains {{...}} syntax
613
- */
614
- static containsHandlebars(template) {
615
- return /\{\{(?!!)[\s\S]*?\}\}/.test(template);
616
- }
617
- /**
618
- * Check if the renderer is initialized.
619
- */
620
- get isInitialized() {
621
- return this.initialized;
622
- }
623
- };
624
- }
625
- });
626
-
627
- // libs/uipack/src/bridge-runtime/iife-generator.ts
628
- function generateBridgeIIFE(options = {}) {
629
- const { debug = false, trustedOrigins = [], minify = false } = options;
630
- const adapters = options.adapters || ["openai", "ext-apps", "claude", "gemini", "generic"];
631
- const parts = [];
632
- parts.push("(function() {");
633
- parts.push('"use strict";');
634
- parts.push("");
635
- if (debug) {
636
- parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }');
637
- } else {
638
- parts.push("function log() {}");
639
- }
640
- parts.push("");
641
- parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");
642
- parts.push("");
643
- parts.push(generateContextDetection());
644
- parts.push("");
645
- parts.push(generateBaseCapabilities());
646
- parts.push("");
647
- if (adapters.includes("openai")) {
648
- parts.push(generateOpenAIAdapter());
649
- parts.push("");
650
- }
651
- if (adapters.includes("ext-apps")) {
652
- parts.push(generateExtAppsAdapter(trustedOrigins));
653
- parts.push("");
654
- }
655
- if (adapters.includes("claude")) {
656
- parts.push(generateClaudeAdapter());
657
- parts.push("");
658
- }
659
- if (adapters.includes("gemini")) {
660
- parts.push(generateGeminiAdapter());
661
- parts.push("");
662
- }
663
- if (adapters.includes("generic")) {
664
- parts.push(generateGenericAdapter());
665
- parts.push("");
666
- }
667
- parts.push(generatePlatformDetection(adapters));
668
- parts.push("");
669
- parts.push(generateBridgeClass());
670
- parts.push("");
671
- parts.push("var bridge = new FrontMcpBridge();");
672
- parts.push("bridge.initialize().then(function() {");
673
- parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');
674
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');
675
- parts.push("}).catch(function(err) {");
676
- parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');
677
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');
678
- parts.push("});");
679
- parts.push("");
680
- parts.push("window.FrontMcpBridge = bridge;");
681
- parts.push("})();");
682
- const code = parts.join("\n");
683
- if (minify) {
684
- return minifyJS(code);
685
- }
686
- return code;
687
- }
688
- function generateContextDetection() {
689
- return `
690
- function detectTheme() {
691
- if (typeof window !== 'undefined' && window.matchMedia) {
692
- return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
693
- }
694
- return 'light';
695
- }
696
-
697
- function detectLocale() {
698
- if (typeof navigator !== 'undefined') {
699
- return navigator.language || 'en-US';
700
- }
701
- return 'en-US';
702
- }
703
-
704
- function detectUserAgent() {
705
- if (typeof navigator === 'undefined') {
706
- return { type: 'web', hover: true, touch: false };
707
- }
708
- var ua = navigator.userAgent || '';
709
- var isMobile = /iPhone|iPad|iPod|Android/i.test(ua);
710
- var hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
711
- var hasHover = window.matchMedia && window.matchMedia('(hover: hover)').matches;
712
- return { type: isMobile ? 'mobile' : 'web', hover: hasHover !== false, touch: hasTouch };
713
- }
714
-
715
- function detectViewport() {
716
- if (typeof window !== 'undefined') {
717
- return { width: window.innerWidth, height: window.innerHeight };
718
- }
719
- return undefined;
720
- }
721
-
722
- function readInjectedData() {
723
- var data = { toolInput: {}, toolOutput: undefined, structuredContent: undefined };
724
- if (typeof window !== 'undefined') {
725
- if (window.__mcpToolInput) data.toolInput = window.__mcpToolInput;
726
- if (window.__mcpToolOutput) data.toolOutput = window.__mcpToolOutput;
727
- if (window.__mcpStructuredContent) data.structuredContent = window.__mcpStructuredContent;
728
- }
729
- return data;
730
- }
731
- `.trim();
732
- }
733
- function generateBaseCapabilities() {
734
- return `
735
- var DEFAULT_CAPABILITIES = {
736
- canCallTools: false,
737
- canSendMessages: false,
738
- canOpenLinks: false,
739
- canPersistState: true,
740
- hasNetworkAccess: true,
741
- supportsDisplayModes: false,
742
- supportsTheme: true
743
- };
744
- `.trim();
745
- }
746
- function generateOpenAIAdapter() {
747
- return `
748
- var OpenAIAdapter = {
749
- id: 'openai',
750
- name: 'OpenAI ChatGPT',
751
- priority: 100,
752
- capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
753
- canCallTools: true,
754
- canSendMessages: true,
755
- canOpenLinks: true,
756
- supportsDisplayModes: true
757
- }),
758
- canHandle: function() {
759
- if (typeof window === 'undefined') return false;
760
- // Check for window.openai.callTool (the actual OpenAI SDK API)
761
- if (window.openai && typeof window.openai.callTool === 'function') return true;
762
- // Also check if we're being injected with tool metadata (OpenAI injects toolOutput)
763
- if (window.openai && (window.openai.toolOutput !== undefined || window.openai.toolInput !== undefined)) return true;
764
- return false;
765
- },
766
- initialize: function(context) {
767
- var sdk = window.openai;
768
- context.sdk = sdk;
769
- // OpenAI SDK exposes theme and displayMode directly as properties
770
- if (sdk.theme) {
771
- context.hostContext.theme = sdk.theme;
772
- }
773
- if (sdk.displayMode) {
774
- context.hostContext.displayMode = sdk.displayMode;
775
- }
776
- // Note: OpenAI SDK does not have an onContextChange equivalent
777
- return Promise.resolve();
778
- },
779
- callTool: function(context, name, args) {
780
- return context.sdk.callTool(name, args);
781
- },
782
- sendMessage: function(context, content) {
783
- if (typeof context.sdk.sendFollowUpMessage === 'function') {
784
- return context.sdk.sendFollowUpMessage(content);
785
- }
786
- return Promise.reject(new Error('Messages not supported'));
787
- },
788
- openLink: function(context, url) {
789
- window.open(url, '_blank', 'noopener,noreferrer');
790
- return Promise.resolve();
791
- },
792
- requestDisplayMode: function(context, mode) {
793
- return Promise.resolve();
794
- },
795
- requestClose: function(context) {
796
- return Promise.resolve();
797
- }
798
- };
799
- `.trim();
800
- }
801
- function generateExtAppsAdapter(trustedOrigins) {
802
- const originsArray = trustedOrigins.length > 0 ? JSON.stringify(trustedOrigins) : "[]";
803
- return `
804
- var ExtAppsAdapter = {
805
- id: 'ext-apps',
806
- name: 'ext-apps (SEP-1865)',
807
- priority: 80,
808
- capabilities: Object.assign({}, DEFAULT_CAPABILITIES, { canPersistState: true, hasNetworkAccess: true }),
809
- trustedOrigins: ${originsArray},
810
- trustedOrigin: null,
811
- originTrustPending: false,
812
- pendingRequests: {},
813
- requestId: 0,
814
- hostCapabilities: {},
815
- canHandle: function() {
816
- if (typeof window === 'undefined') return false;
817
- if (window.parent === window) return false;
818
-
819
- // Check for OpenAI SDK - defer to OpenAIAdapter
820
- if (window.openai && window.openai.canvas) return false;
821
- if (window.openai && typeof window.openai.callTool === 'function') return false;
822
-
823
- // Explicit ext-apps marker
824
- if (window.__mcpPlatform === 'ext-apps') return true;
825
- if (window.__extAppsInitialized) return true;
826
-
827
- // Claude MCP Apps mode (2026+) - uses ext-apps protocol
828
- if (window.__mcpAppsEnabled) return true;
829
-
830
- // Legacy Claude detection - defer to ClaudeAdapter
831
- if (window.claude) return false;
832
- if (window.__claudeArtifact) return false;
833
- if (window.__mcpPlatform === 'claude') return false;
834
- if (typeof location !== 'undefined') {
835
- try {
836
- var url = new URL(location.href);
837
- var hostname = url.hostname.toLowerCase();
838
- var isClaudeHost = hostname === 'claude.ai' || (hostname.length > 10 && hostname.slice(-10) === '.claude.ai');
839
- var isAnthropicHost = hostname === 'anthropic.com' || (hostname.length > 14 && hostname.slice(-14) === '.anthropic.com');
840
- if (isClaudeHost || isAnthropicHost) return false;
841
- } catch (e) {
842
- // If URL parsing fails, fall through to other checks
843
- }
844
- }
845
-
846
- // Do NOT default to true for any iframe
847
- return false;
848
- },
849
- initialize: function(context) {
850
- var self = this;
851
- context.extApps = this;
852
-
853
- window.addEventListener('message', function(event) {
854
- self.handleMessage(context, event);
855
- });
856
-
857
- return self.performHandshake(context);
858
- },
859
- handleMessage: function(context, event) {
860
- if (!this.isOriginTrusted(event.origin)) return;
861
- var data = event.data;
862
- if (!data || typeof data !== 'object' || data.jsonrpc !== '2.0') return;
863
-
864
- if ('id' in data && (data.result !== undefined || data.error !== undefined)) {
865
- var pending = this.pendingRequests[data.id];
866
- if (pending) {
867
- clearTimeout(pending.timeout);
868
- delete this.pendingRequests[data.id];
869
- if (data.error) {
870
- pending.reject(new Error(data.error.message + ' (code: ' + data.error.code + ')'));
871
- } else {
872
- pending.resolve(data.result);
873
- }
874
- }
875
- return;
876
- }
877
-
878
- if ('method' in data && !('id' in data)) {
879
- this.handleNotification(context, data);
880
- }
881
- },
882
- handleNotification: function(context, notification) {
883
- var params = notification.params || {};
884
- switch (notification.method) {
885
- case 'ui/notifications/tool-input':
886
- context.toolInput = params.arguments || {};
887
- window.dispatchEvent(new CustomEvent('tool:input', { detail: { arguments: context.toolInput } }));
888
- break;
889
- case 'ui/notifications/tool-input-partial':
890
- // Streaming: merge partial input with existing
891
- context.toolInput = Object.assign({}, context.toolInput, params.arguments || {});
892
- window.dispatchEvent(new CustomEvent('tool:input-partial', { detail: { arguments: context.toolInput } }));
893
- break;
894
- case 'ui/notifications/tool-result':
895
- context.toolOutput = params.content;
896
- context.structuredContent = params.structuredContent;
897
- context.notifyToolResult(params.content);
898
- window.dispatchEvent(new CustomEvent('tool:result', { detail: params }));
899
- break;
900
- case 'ui/notifications/host-context-changed':
901
- Object.assign(context.hostContext, params);
902
- context.notifyContextChange(params);
903
- break;
904
- case 'ui/notifications/cancelled':
905
- window.dispatchEvent(new CustomEvent('tool:cancelled', { detail: { reason: params.reason } }));
906
- break;
907
- }
908
- },
909
- isOriginTrusted: function(origin) {
910
- if (this.trustedOrigins.length > 0) {
911
- return this.trustedOrigins.indexOf(origin) !== -1;
912
- }
913
- // Trust-on-first-use: trust first message origin.
914
- // SECURITY WARNING: For production, always configure trustedOrigins.
915
- if (!this.trustedOrigin) {
916
- // Guard against race condition where multiple messages arrive simultaneously
917
- if (this.originTrustPending) {
918
- return false;
919
- }
920
- if (window.parent !== window && origin) {
921
- this.originTrustPending = true;
922
- this.trustedOrigin = origin;
923
- this.originTrustPending = false; // Reset after successful trust establishment
924
- return true;
925
- }
926
- return false;
927
- }
928
- return this.trustedOrigin === origin;
929
- },
930
- sendRequest: function(method, params) {
931
- var self = this;
932
- return new Promise(function(resolve, reject) {
933
- // Security: Require trusted origin before sending requests to prevent message leaks
934
- if (!self.trustedOrigin && self.trustedOrigins.length === 0) {
935
- reject(new Error('Cannot send request: no trusted origin established'));
936
- return;
937
- }
938
-
939
- var id = ++self.requestId;
940
- var timeout = setTimeout(function() {
941
- delete self.pendingRequests[id];
942
- reject(new Error('Request ' + method + ' timed out'));
943
- }, 10000);
944
-
945
- self.pendingRequests[id] = { resolve: resolve, reject: reject, timeout: timeout };
946
-
947
- var targetOrigin = self.trustedOrigin || self.trustedOrigins[0];
948
- window.parent.postMessage({ jsonrpc: '2.0', id: id, method: method, params: params }, targetOrigin);
949
- });
950
- },
951
- performHandshake: function(context) {
952
- var self = this;
953
- var params = {
954
- appInfo: { name: 'FrontMCP Widget', version: '1.0.0' },
955
- appCapabilities: { tools: { listChanged: false } },
956
- protocolVersion: '2024-11-05'
957
- };
958
-
959
- return this.sendRequest('ui/initialize', params).then(function(result) {
960
- self.hostCapabilities = result.hostCapabilities || {};
961
- self.capabilities = Object.assign({}, self.capabilities, {
962
- canCallTools: Boolean(self.hostCapabilities.serverToolProxy),
963
- canSendMessages: true,
964
- canOpenLinks: Boolean(self.hostCapabilities.openLink),
965
- supportsDisplayModes: true
966
- });
967
- if (result.hostContext) {
968
- Object.assign(context.hostContext, result.hostContext);
969
- }
970
- });
971
- },
972
- callTool: function(context, name, args) {
973
- if (!this.hostCapabilities.serverToolProxy) {
974
- return Promise.reject(new Error('Server tool proxy not supported'));
975
- }
976
- return this.sendRequest('ui/callServerTool', { name: name, arguments: args });
977
- },
978
- sendMessage: function(context, content) {
979
- return this.sendRequest('ui/message', { content: content });
980
- },
981
- openLink: function(context, url) {
982
- if (!this.hostCapabilities.openLink) {
983
- window.open(url, '_blank', 'noopener,noreferrer');
984
- return Promise.resolve();
985
- }
986
- return this.sendRequest('ui/openLink', { url: url });
987
- },
988
- requestDisplayMode: function(context, mode) {
989
- return this.sendRequest('ui/setDisplayMode', { mode: mode });
990
- },
991
- requestClose: function(context) {
992
- return this.sendRequest('ui/close', {});
993
- },
994
- // Extended ext-apps methods (full specification)
995
- updateModelContext: function(context, data, merge) {
996
- if (!this.hostCapabilities.modelContextUpdate) {
997
- return Promise.reject(new Error('Model context update not supported'));
998
- }
999
- return this.sendRequest('ui/updateModelContext', { context: data, merge: merge !== false });
1000
- },
1001
- log: function(context, level, message, data) {
1002
- if (!this.hostCapabilities.logging) {
1003
- // Fallback to console logging if host doesn't support it
1004
- var logFn = console[level] || console.log;
1005
- logFn('[Widget] ' + message, data);
1006
- return Promise.resolve();
1007
- }
1008
- return this.sendRequest('ui/log', { level: level, message: message, data: data });
1009
- },
1010
- registerTool: function(context, name, description, inputSchema) {
1011
- if (!this.hostCapabilities.widgetTools) {
1012
- return Promise.reject(new Error('Widget tool registration not supported'));
1013
- }
1014
- return this.sendRequest('ui/registerTool', { name: name, description: description, inputSchema: inputSchema });
1015
- },
1016
- unregisterTool: function(context, name) {
1017
- if (!this.hostCapabilities.widgetTools) {
1018
- return Promise.reject(new Error('Widget tool unregistration not supported'));
1019
- }
1020
- return this.sendRequest('ui/unregisterTool', { name: name });
1021
- }
1022
- };
1023
- `.trim();
1024
- }
1025
- function generateClaudeAdapter() {
1026
- return `
1027
- var ClaudeAdapter = {
1028
- id: 'claude',
1029
- name: 'Claude (Anthropic)',
1030
- priority: 60,
1031
- capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1032
- canCallTools: false,
1033
- canSendMessages: false,
1034
- canOpenLinks: true,
1035
- hasNetworkAccess: false,
1036
- supportsDisplayModes: false
1037
- }),
1038
- canHandle: function() {
1039
- if (typeof window === 'undefined') return false;
1040
-
1041
- // If MCP Apps is enabled, let ext-apps adapter handle it
1042
- if (window.__mcpAppsEnabled) return false;
1043
- if (window.__mcpPlatform === 'ext-apps') return false;
1044
- if (window.__extAppsInitialized) return false;
1045
-
1046
- // Legacy Claude detection
1047
- if (window.__mcpPlatform === 'claude') return true;
1048
- if (window.claude) return true;
1049
- if (window.__claudeArtifact) return true;
1050
- if (typeof location !== 'undefined') {
1051
- try {
1052
- var url = new URL(location.href);
1053
- var hostname = url.hostname.toLowerCase();
1054
- var isClaudeHost = hostname === 'claude.ai' || (hostname.length > 10 && hostname.slice(-10) === '.claude.ai');
1055
- var isAnthropicHost = hostname === 'anthropic.com' || (hostname.length > 14 && hostname.slice(-14) === '.anthropic.com');
1056
- if (isClaudeHost || isAnthropicHost) return true;
1057
- } catch (e) {
1058
- // If URL parsing fails, fall through
1059
- }
1060
- }
1061
- return false;
1062
- },
1063
- initialize: function(context) {
1064
- return Promise.resolve();
1065
- },
1066
- callTool: function() {
1067
- return Promise.reject(new Error('Tool calls not supported in Claude'));
1068
- },
1069
- sendMessage: function() {
1070
- return Promise.reject(new Error('Messages not supported in Claude'));
1071
- },
1072
- openLink: function(context, url) {
1073
- window.open(url, '_blank', 'noopener,noreferrer');
1074
- return Promise.resolve();
1075
- },
1076
- requestDisplayMode: function() {
1077
- return Promise.resolve();
1078
- },
1079
- requestClose: function() {
1080
- return Promise.resolve();
1081
- }
1082
- };
1083
- `.trim();
1084
- }
1085
- function generateGeminiAdapter() {
1086
- return `
1087
- var GeminiAdapter = {
1088
- id: 'gemini',
1089
- name: 'Google Gemini',
1090
- priority: 40,
1091
- capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1092
- canOpenLinks: true,
1093
- hasNetworkAccess: true
1094
- }),
1095
- canHandle: function() {
1096
- if (typeof window === 'undefined') return false;
1097
- if (window.__mcpPlatform === 'gemini') return true;
1098
- if (window.gemini) return true;
1099
- if (typeof location !== 'undefined') {
1100
- var href = location.href;
1101
- if (href.indexOf('gemini.google.com') !== -1 || href.indexOf('bard.google.com') !== -1) return true;
1102
- }
1103
- return false;
1104
- },
1105
- initialize: function(context) {
1106
- if (window.gemini && window.gemini.ui && window.gemini.ui.getTheme) {
1107
- context.hostContext.theme = window.gemini.ui.getTheme() === 'dark' ? 'dark' : 'light';
1108
- }
1109
- return Promise.resolve();
1110
- },
1111
- callTool: function() {
1112
- return Promise.reject(new Error('Tool calls not supported in Gemini'));
1113
- },
1114
- sendMessage: function(context, content) {
1115
- if (window.gemini && window.gemini.ui && window.gemini.ui.sendMessage) {
1116
- return window.gemini.ui.sendMessage(content);
1117
- }
1118
- return Promise.reject(new Error('Messages not supported in Gemini'));
1119
- },
1120
- openLink: function(context, url) {
1121
- if (window.gemini && window.gemini.ui && window.gemini.ui.openLink) {
1122
- return window.gemini.ui.openLink(url);
1123
- }
1124
- window.open(url, '_blank', 'noopener,noreferrer');
1125
- return Promise.resolve();
1126
- },
1127
- requestDisplayMode: function() {
1128
- return Promise.resolve();
1129
- },
1130
- requestClose: function() {
1131
- return Promise.resolve();
1132
- }
1133
- };
1134
- `.trim();
1135
- }
1136
- function generateGenericAdapter() {
1137
- return `
1138
- var GenericAdapter = {
1139
- id: 'generic',
1140
- name: 'Generic Web',
1141
- priority: 0,
1142
- capabilities: Object.assign({}, DEFAULT_CAPABILITIES, {
1143
- canOpenLinks: true,
1144
- hasNetworkAccess: true
1145
- }),
1146
- canHandle: function() {
1147
- return typeof window !== 'undefined';
1148
- },
1149
- initialize: function(context) {
1150
- return Promise.resolve();
1151
- },
1152
- callTool: function() {
1153
- return Promise.reject(new Error('Tool calls not supported'));
1154
- },
1155
- sendMessage: function() {
1156
- return Promise.reject(new Error('Messages not supported'));
1157
- },
1158
- openLink: function(context, url) {
1159
- window.open(url, '_blank', 'noopener,noreferrer');
1160
- return Promise.resolve();
1161
- },
1162
- requestDisplayMode: function() {
1163
- return Promise.resolve();
1164
- },
1165
- requestClose: function() {
1166
- return Promise.resolve();
1167
- }
1168
- };
1169
- `.trim();
1170
- }
1171
- function generatePlatformDetection(adapters) {
1172
- const adapterVars = adapters.map((a) => {
1173
- switch (a) {
1174
- case "openai":
1175
- return "OpenAIAdapter";
1176
- case "ext-apps":
1177
- return "ExtAppsAdapter";
1178
- case "claude":
1179
- return "ClaudeAdapter";
1180
- case "gemini":
1181
- return "GeminiAdapter";
1182
- case "generic":
1183
- return "GenericAdapter";
1184
- default:
1185
- return "";
1186
- }
1187
- }).filter(Boolean);
1188
- return `
1189
- var ADAPTERS = [${adapterVars.join(", ")}].sort(function(a, b) { return b.priority - a.priority; });
1190
-
1191
- function detectPlatform() {
1192
- for (var i = 0; i < ADAPTERS.length; i++) {
1193
- if (ADAPTERS[i].canHandle()) {
1194
- log('Detected platform: ' + ADAPTERS[i].id);
1195
- return ADAPTERS[i];
1196
- }
1197
- }
1198
- log('No platform detected, using generic');
1199
- return GenericAdapter;
1200
- }
1201
- `.trim();
1202
- }
1203
- function generateBridgeClass() {
1204
- return `
1205
- function FrontMcpBridge() {
1206
- this._adapter = null;
1207
- this._initialized = false;
1208
- this._context = {
1209
- hostContext: {
1210
- theme: detectTheme(),
1211
- displayMode: 'inline',
1212
- locale: detectLocale(),
1213
- userAgent: detectUserAgent(),
1214
- safeArea: DEFAULT_SAFE_AREA,
1215
- viewport: detectViewport()
1216
- },
1217
- toolInput: {},
1218
- toolOutput: undefined,
1219
- structuredContent: undefined,
1220
- widgetState: {},
1221
- contextListeners: [],
1222
- toolResultListeners: [],
1223
- notifyContextChange: function(changes) {
1224
- Object.assign(this.hostContext, changes);
1225
- for (var i = 0; i < this.contextListeners.length; i++) {
1226
- try { this.contextListeners[i](changes); } catch(e) {}
1227
- }
1228
- },
1229
- notifyToolResult: function(result) {
1230
- this.toolOutput = result;
1231
- for (var i = 0; i < this.toolResultListeners.length; i++) {
1232
- try { this.toolResultListeners[i](result); } catch(e) {}
1233
- }
1234
- }
1235
- };
1236
-
1237
- var injected = readInjectedData();
1238
- this._context.toolInput = injected.toolInput;
1239
- this._context.toolOutput = injected.toolOutput;
1240
- this._context.structuredContent = injected.structuredContent;
1241
-
1242
- this._loadWidgetState();
1243
- }
1244
-
1245
- FrontMcpBridge.prototype._loadWidgetState = function() {
1246
- try {
1247
- var key = 'frontmcp:widget:' + (window.__mcpToolName || 'unknown');
1248
- var stored = localStorage.getItem(key);
1249
- if (stored) this._context.widgetState = JSON.parse(stored);
1250
- } catch(e) {}
1251
- };
1252
-
1253
- FrontMcpBridge.prototype._saveWidgetState = function() {
1254
- try {
1255
- var key = 'frontmcp:widget:' + (window.__mcpToolName || 'unknown');
1256
- localStorage.setItem(key, JSON.stringify(this._context.widgetState));
1257
- } catch(e) {}
1258
- };
1259
-
1260
- FrontMcpBridge.prototype.initialize = function() {
1261
- if (this._initialized) return Promise.resolve();
1262
- var self = this;
1263
- this._adapter = detectPlatform();
1264
- return this._adapter.initialize(this._context).then(function() {
1265
- self._initialized = true;
1266
- // Set up the data-tool-call click handler after initialization
1267
- self._setupDataToolCallHandler();
1268
- });
1269
- };
1270
-
1271
- Object.defineProperty(FrontMcpBridge.prototype, 'initialized', { get: function() { return this._initialized; } });
1272
- Object.defineProperty(FrontMcpBridge.prototype, 'adapterId', { get: function() { return this._adapter ? this._adapter.id : undefined; } });
1273
- Object.defineProperty(FrontMcpBridge.prototype, 'capabilities', { get: function() { return this._adapter ? this._adapter.capabilities : DEFAULT_CAPABILITIES; } });
1274
-
1275
- FrontMcpBridge.prototype.getTheme = function() { return this._context.hostContext.theme; };
1276
- FrontMcpBridge.prototype.getDisplayMode = function() { return this._context.hostContext.displayMode; };
1277
- FrontMcpBridge.prototype.getToolInput = function() { return this._context.toolInput; };
1278
- FrontMcpBridge.prototype.getToolOutput = function() { return this._context.toolOutput; };
1279
- FrontMcpBridge.prototype.getStructuredContent = function() { return this._context.structuredContent; };
1280
- FrontMcpBridge.prototype.getWidgetState = function() { return this._context.widgetState; };
1281
- FrontMcpBridge.prototype.getHostContext = function() { return Object.assign({}, this._context.hostContext); };
1282
- FrontMcpBridge.prototype.hasCapability = function(cap) { return this._adapter && this._adapter.capabilities[cap] === true; };
1283
-
1284
- // Get tool response metadata (platform-agnostic)
1285
- // Used by inline mode widgets to detect when ui/html arrives
1286
- FrontMcpBridge.prototype.getToolResponseMetadata = function() {
1287
- // OpenAI injects toolResponseMetadata for widget-producing tools
1288
- if (typeof window !== 'undefined' && window.openai && window.openai.toolResponseMetadata) {
1289
- return window.openai.toolResponseMetadata;
1290
- }
1291
- // Claude (future support)
1292
- if (typeof window !== 'undefined' && window.claude && window.claude.toolResponseMetadata) {
1293
- return window.claude.toolResponseMetadata;
1294
- }
1295
- // FrontMCP direct injection (for testing/ext-apps)
1296
- if (typeof window !== 'undefined' && window.__mcpToolResponseMetadata) {
1297
- return window.__mcpToolResponseMetadata;
1298
- }
1299
- return null;
1300
- };
1301
-
1302
- // Subscribe to tool response metadata changes (for inline mode injection)
1303
- FrontMcpBridge.prototype.onToolResponseMetadata = function(callback) {
1304
- var self = this;
1305
- var called = false;
1306
-
1307
- // Check if already available
1308
- var existing = self.getToolResponseMetadata();
1309
- if (existing) {
1310
- called = true;
1311
- callback(existing);
1312
- }
1313
-
1314
- // Set up property interceptors for OpenAI
1315
- if (typeof window !== 'undefined') {
1316
- // OpenAI: Intercept toolResponseMetadata assignment
1317
- if (!window.__frontmcpMetadataIntercepted) {
1318
- window.__frontmcpMetadataIntercepted = true;
1319
- window.__frontmcpMetadataCallbacks = [];
1320
-
1321
- // Create openai object if it doesn't exist
1322
- if (!window.openai) window.openai = {};
1323
-
1324
- var originalMetadata = window.openai.toolResponseMetadata;
1325
- Object.defineProperty(window.openai, 'toolResponseMetadata', {
1326
- get: function() { return originalMetadata; },
1327
- set: function(val) {
1328
- originalMetadata = val;
1329
- log('toolResponseMetadata set, notifying ' + window.__frontmcpMetadataCallbacks.length + ' listeners');
1330
- for (var i = 0; i < window.__frontmcpMetadataCallbacks.length; i++) {
1331
- try { window.__frontmcpMetadataCallbacks[i](val); } catch(e) {}
1332
- }
1333
- },
1334
- configurable: true
1335
- });
1336
- }
1337
-
1338
- // Register callback wrapper (store reference for unsubscribe)
1339
- var wrapper = function(metadata) {
1340
- if (!called) {
1341
- called = true;
1342
- callback(metadata);
1343
- }
1344
- };
1345
- window.__frontmcpMetadataCallbacks.push(wrapper);
1346
-
1347
- // Return unsubscribe function that removes the wrapper (not the original callback)
1348
- return function() {
1349
- if (window.__frontmcpMetadataCallbacks) {
1350
- var idx = window.__frontmcpMetadataCallbacks.indexOf(wrapper);
1351
- if (idx !== -1) window.__frontmcpMetadataCallbacks.splice(idx, 1);
1352
- }
1353
- };
1354
- }
1355
-
1356
- // Return no-op unsubscribe for non-window environments
1357
- return function() {};
1358
- };
1359
-
1360
- FrontMcpBridge.prototype.callTool = function(name, args) {
1361
- // Priority 1: Direct OpenAI SDK call (most reliable in OpenAI iframe)
1362
- // This bypasses adapter abstraction for maximum compatibility
1363
- if (typeof window !== 'undefined' && window.openai && typeof window.openai.callTool === 'function') {
1364
- log('callTool: Using OpenAI SDK directly');
1365
- return window.openai.callTool(name, args);
1366
- }
1367
-
1368
- // Priority 2: Use adapter (if initialized and supports tool calls)
1369
- if (this._adapter && this._adapter.capabilities && this._adapter.capabilities.canCallTools) {
1370
- log('callTool: Using adapter ' + this._adapter.id);
1371
- return this._adapter.callTool(this._context, name, args);
1372
- }
1373
-
1374
- // Not initialized or no tool support
1375
- if (!this._adapter) {
1376
- return Promise.reject(new Error('Bridge not initialized. Wait for bridge:ready event.'));
1377
- }
1378
- return Promise.reject(new Error('Tool calls not supported on this platform (' + this._adapter.id + ')'));
1379
- };
1380
-
1381
- FrontMcpBridge.prototype.sendMessage = function(content) {
1382
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1383
- return this._adapter.sendMessage(this._context, content);
1384
- };
1385
-
1386
- FrontMcpBridge.prototype.openLink = function(url) {
1387
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1388
- return this._adapter.openLink(this._context, url);
1389
- };
1390
-
1391
- FrontMcpBridge.prototype.requestDisplayMode = function(mode) {
1392
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1393
- var self = this;
1394
- return this._adapter.requestDisplayMode(this._context, mode).then(function() {
1395
- self._context.hostContext.displayMode = mode;
1396
- });
1397
- };
1398
-
1399
- FrontMcpBridge.prototype.requestClose = function() {
1400
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1401
- return this._adapter.requestClose(this._context);
1402
- };
1403
-
1404
- // Extended ext-apps methods (full specification)
1405
- FrontMcpBridge.prototype.updateModelContext = function(context, merge) {
1406
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1407
- if (!this._adapter.updateModelContext) {
1408
- return Promise.reject(new Error('updateModelContext not supported on this platform'));
1409
- }
1410
- return this._adapter.updateModelContext(this._context, context, merge);
1411
- };
1412
-
1413
- FrontMcpBridge.prototype.log = function(level, message, data) {
1414
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1415
- if (!this._adapter.log) {
1416
- // Fallback to console
1417
- var logFn = console[level] || console.log;
1418
- logFn('[Widget] ' + message, data);
1419
- return Promise.resolve();
1420
- }
1421
- return this._adapter.log(this._context, level, message, data);
1422
- };
1423
-
1424
- FrontMcpBridge.prototype.registerTool = function(name, description, inputSchema) {
1425
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1426
- if (!this._adapter.registerTool) {
1427
- return Promise.reject(new Error('registerTool not supported on this platform'));
1428
- }
1429
- return this._adapter.registerTool(this._context, name, description, inputSchema);
1430
- };
1431
-
1432
- FrontMcpBridge.prototype.unregisterTool = function(name) {
1433
- if (!this._adapter) return Promise.reject(new Error('Not initialized'));
1434
- if (!this._adapter.unregisterTool) {
1435
- return Promise.reject(new Error('unregisterTool not supported on this platform'));
1436
- }
1437
- return this._adapter.unregisterTool(this._context, name);
1438
- };
1439
-
1440
- FrontMcpBridge.prototype.setWidgetState = function(state) {
1441
- Object.assign(this._context.widgetState, state);
1442
- this._saveWidgetState();
1443
- };
1444
-
1445
- FrontMcpBridge.prototype.onContextChange = function(callback) {
1446
- var listeners = this._context.contextListeners;
1447
- listeners.push(callback);
1448
- return function() {
1449
- var idx = listeners.indexOf(callback);
1450
- if (idx !== -1) listeners.splice(idx, 1);
1451
- };
1452
- };
1453
-
1454
- FrontMcpBridge.prototype.onToolResult = function(callback) {
1455
- var listeners = this._context.toolResultListeners;
1456
- listeners.push(callback);
1457
- return function() {
1458
- var idx = listeners.indexOf(callback);
1459
- if (idx !== -1) listeners.splice(idx, 1);
1460
- };
1461
- };
1462
-
1463
- // ==================== data-tool-call Click Handler ====================
1464
-
1465
- FrontMcpBridge.prototype._setupDataToolCallHandler = function() {
1466
- var self = this;
1467
-
1468
- document.addEventListener('click', function(e) {
1469
- // Find the closest element with data-tool-call attribute
1470
- var target = e.target;
1471
- while (target && target !== document) {
1472
- if (target.hasAttribute && target.hasAttribute('data-tool-call')) {
1473
- var toolName = target.getAttribute('data-tool-call');
1474
- var argsAttr = target.getAttribute('data-tool-args');
1475
- var args = {};
1476
-
1477
- try {
1478
- if (argsAttr) {
1479
- args = JSON.parse(argsAttr);
1480
- }
1481
- } catch (parseErr) {
1482
- console.error('[frontmcp] Failed to parse data-tool-args:', parseErr);
1483
- }
1484
-
1485
- log('data-tool-call clicked: ' + toolName);
1486
-
1487
- // Show loading state - save original content first
1488
- var originalContent = target.innerHTML;
1489
- var originalDisabled = target.disabled;
1490
- target.disabled = true;
1491
- target.classList.add('opacity-50', 'cursor-not-allowed');
1492
-
1493
- // Add spinner for buttons
1494
- var spinner = '<svg class="animate-spin -ml-1 mr-2 h-4 w-4 inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>';
1495
- if (target.tagName === 'BUTTON') {
1496
- target.innerHTML = spinner + 'Loading...';
1497
- }
1498
-
1499
- // Helper to reset button state
1500
- function resetButton() {
1501
- target.innerHTML = originalContent;
1502
- target.disabled = originalDisabled;
1503
- target.classList.remove('opacity-50', 'cursor-not-allowed');
1504
- }
1505
-
1506
- // Determine how to call the tool
1507
- var toolCallPromise;
1508
-
1509
- // Priority 1: Direct OpenAI SDK call (bypasses adapter abstraction)
1510
- if (typeof window !== 'undefined' && window.openai && typeof window.openai.callTool === 'function') {
1511
- log('Using OpenAI SDK directly for tool call');
1512
- toolCallPromise = window.openai.callTool(toolName, args);
1513
- }
1514
- // Priority 2: Use adapter (if it supports tool calls)
1515
- else if (self.hasCapability('canCallTools')) {
1516
- log('Using adapter for tool call');
1517
- toolCallPromise = self.callTool(toolName, args);
1518
- }
1519
- // No tool call capability
1520
- else {
1521
- console.error('[frontmcp] Tool calls not supported on this platform (' + self.adapterId + ')');
1522
- resetButton();
1523
- target.dispatchEvent(new CustomEvent('tool:error', {
1524
- detail: { name: toolName, args: args, error: 'Tool calls not supported on this platform' },
1525
- bubbles: true
1526
- }));
1527
- e.preventDefault();
1528
- return;
1529
- }
1530
-
1531
- // Handle the tool call result
1532
- toolCallPromise.then(function(result) {
1533
- log('Tool call succeeded: ' + toolName);
1534
- resetButton();
1535
-
1536
- // Update bridge state to trigger widget re-render
1537
- // React isn't hydrated in OpenAI iframe, so useState doesn't work
1538
- // Instead, we use the bridge's reactive state system
1539
- if (result && window.__frontmcp && window.__frontmcp.bridge && typeof window.__frontmcp.bridge.setWidgetState === 'function') {
1540
- var newData = result.structuredContent || result;
1541
- log('Updating bridge state with new data');
1542
- window.__frontmcp.bridge.setWidgetState(newData);
1543
- }
1544
-
1545
- // Dispatch success event
1546
- target.dispatchEvent(new CustomEvent('tool:success', {
1547
- detail: { name: toolName, args: args, result: result },
1548
- bubbles: true
1549
- }));
1550
- }).catch(function(err) {
1551
- console.error('[frontmcp] Tool call failed: ' + toolName, err);
1552
- resetButton();
1553
- // Dispatch error event
1554
- target.dispatchEvent(new CustomEvent('tool:error', {
1555
- detail: { name: toolName, args: args, error: err.message || err },
1556
- bubbles: true
1557
- }));
1558
- });
1559
-
1560
- // Prevent default behavior (e.g., form submission)
1561
- e.preventDefault();
1562
- return;
1563
- }
1564
- target = target.parentElement;
1565
- }
1566
- }, true); // Use capture phase to handle before React handlers
1567
- };
1568
- `.trim();
1569
- }
1570
- var MAX_MINIFY_CODE_LENGTH = 5e5;
1571
- function minifyJS(code) {
1572
- if (code.length > MAX_MINIFY_CODE_LENGTH) {
1573
- return code;
1574
- }
1575
- return code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/.*$/gm, "").replace(/\s+/g, " ").replace(/\s*([{};,:()[\]])\s*/g, "$1").replace(/;\}/g, "}").trim();
1576
- }
1577
- function generatePlatformBundle(platform, options = {}) {
1578
- const platformAdapters = {
1579
- chatgpt: ["openai", "generic"],
1580
- claude: ["claude", "generic"],
1581
- gemini: ["gemini", "generic"],
1582
- universal: ["openai", "ext-apps", "claude", "gemini", "generic"]
1583
- };
1584
- return generateBridgeIIFE({
1585
- ...options,
1586
- adapters: platformAdapters[platform]
1587
- });
1588
- }
1589
- var UNIVERSAL_BRIDGE_SCRIPT = generateBridgeIIFE();
1590
- var BRIDGE_SCRIPT_TAGS = {
1591
- universal: `<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,
1592
- chatgpt: `<script>${generatePlatformBundle("chatgpt")}</script>`,
1593
- claude: `<script>${generatePlatformBundle("claude")}</script>`,
1594
- gemini: `<script>${generatePlatformBundle("gemini")}</script>`
1595
- };
1596
-
1597
- // libs/uipack/src/runtime/mcp-bridge.ts
1598
- var MCP_BRIDGE_RUNTIME = `
1599
- <script>
1600
- (function() {
1601
- 'use strict';
1602
-
1603
- // ==================== Environment Detection ====================
1604
-
1605
- var isOpenAI = typeof window.openai !== 'undefined';
1606
- var isExtApps = window.parent !== window && !isOpenAI;
1607
- var isClaude = typeof window.claude !== 'undefined' ||
1608
- (window.__mcpPlatform === 'claude');
1609
- var isGemini = window.__mcpPlatform === 'gemini';
1610
-
1611
- // ==================== Internal State ====================
1612
-
1613
- var messageId = 0;
1614
- var pendingRequests = new Map();
1615
- var contextChangeListeners = [];
1616
- var toolResultListeners = [];
1617
-
1618
- // Default values for polyfilled properties
1619
- var defaultSafeArea = { top: 0, bottom: 0, left: 0, right: 0 };
1620
- var defaultUserAgent = { type: 'web', hover: true, touch: false };
1621
-
1622
- // Host context (for ext-apps and polyfill mode)
1623
- var hostContext = window.__mcpHostContext || {
1624
- theme: 'light',
1625
- displayMode: 'inline'
1626
- };
1627
-
1628
- // Trusted origin for postMessage validation (set during ext-apps initialization)
1629
- var trustedOrigin = null;
1630
-
1631
- // Detect device capabilities
1632
- var detectUserAgent = function() {
1633
- var ua = navigator.userAgent || '';
1634
- var isMobile = /iPhone|iPad|iPod|Android/i.test(ua);
1635
- var hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
1636
- var hasHover = window.matchMedia && window.matchMedia('(hover: hover)').matches;
1637
- return {
1638
- type: isMobile ? 'mobile' : 'web',
1639
- hover: hasHover !== false,
1640
- touch: hasTouch
1641
- };
1642
- };
1643
-
1644
- // Detect theme from system preference
1645
- var detectTheme = function() {
1646
- if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
1647
- return 'dark';
1648
- }
1649
- return 'light';
1650
- };
1651
-
1652
- // ==================== Bridge Implementation ====================
1653
-
1654
- /**
1655
- * MCP Bridge provides full OpenAI API compatibility.
1656
- * On OpenAI, it proxies directly to window.openai.
1657
- * On other platforms, it provides polyfills.
1658
- */
1659
- var bridge = {
1660
- // ==================== Environment Info ====================
1661
-
1662
- get provider() {
1663
- if (isOpenAI) return 'openai';
1664
- if (isClaude) return 'claude';
1665
- if (isGemini) return 'gemini';
1666
- if (isExtApps) return 'ext-apps';
1667
- return 'unknown';
1668
- },
1669
-
1670
- // ==================== OpenAI-Compatible Properties ====================
1671
-
1672
- get theme() {
1673
- if (isOpenAI && window.openai) {
1674
- return window.openai.theme || 'light';
1675
- }
1676
- return hostContext.theme || detectTheme();
1677
- },
1678
-
1679
- get userAgent() {
1680
- if (isOpenAI && window.openai && window.openai.userAgent) {
1681
- return window.openai.userAgent;
1682
- }
1683
- return hostContext.userAgent || detectUserAgent();
1684
- },
1685
-
1686
- get locale() {
1687
- if (isOpenAI && window.openai && window.openai.locale) {
1688
- return window.openai.locale;
1689
- }
1690
- return navigator.language || 'en-US';
1691
- },
1692
-
1693
- get maxHeight() {
1694
- if (isOpenAI && window.openai) {
1695
- return window.openai.maxHeight;
1696
- }
1697
- return hostContext.viewport ? hostContext.viewport.maxHeight : undefined;
1698
- },
1699
-
1700
- get displayMode() {
1701
- if (isOpenAI && window.openai) {
1702
- return window.openai.displayMode || 'inline';
1703
- }
1704
- return hostContext.displayMode || 'inline';
1705
- },
1706
-
1707
- get safeArea() {
1708
- if (isOpenAI && window.openai && window.openai.safeArea) {
1709
- return window.openai.safeArea;
1710
- }
1711
- return hostContext.safeArea || defaultSafeArea;
1712
- },
1713
-
1714
- get toolInput() {
1715
- if (isOpenAI && window.openai && window.openai.toolInput) {
1716
- return window.openai.toolInput;
1717
- }
1718
- return window.__mcpToolInput || {};
1719
- },
1720
-
1721
- get toolOutput() {
1722
- if (isOpenAI && window.openai) {
1723
- return window.openai.toolOutput;
1724
- }
1725
- return window.__mcpToolOutput;
1726
- },
1727
-
1728
- get structuredContent() {
1729
- // Alias for toolOutput to maintain compatibility
1730
- if (isOpenAI && window.openai) {
1731
- return window.openai.toolOutput;
1732
- }
1733
- return window.__mcpStructuredContent;
1734
- },
1735
-
1736
- get toolResponseMetadata() {
1737
- if (isOpenAI && window.openai && window.openai.toolResponseMetadata) {
1738
- return window.openai.toolResponseMetadata;
1739
- }
1740
- return window.__mcpToolResponseMetadata || {};
1741
- },
1742
-
1743
- get widgetState() {
1744
- if (isOpenAI && window.openai) {
1745
- return window.openai.widgetState || {};
1746
- }
1747
- // Polyfill: use localStorage
1748
- try {
1749
- var stored = localStorage.getItem('__mcpWidgetState');
1750
- return stored ? JSON.parse(stored) : {};
1751
- } catch (e) {
1752
- return {};
1753
- }
1754
- },
1755
-
1756
- // ==================== OpenAI-Compatible Methods ====================
1757
-
1758
- callTool: function(name, params) {
1759
- if (isOpenAI && window.openai && window.openai.callTool) {
1760
- return window.openai.callTool(name, params);
1761
- }
1762
- if (isClaude) {
1763
- return Promise.reject(new Error(
1764
- 'Tool calls are not supported in Claude widgets (network-blocked sandbox)'
1765
- ));
1766
- }
1767
- if (isGemini) {
1768
- return Promise.reject(new Error(
1769
- 'Tool calls are not supported in Gemini widgets'
1770
- ));
1771
- }
1772
- if (isExtApps) {
1773
- return this._sendRequest('tools/call', { name: name, arguments: params });
1774
- }
1775
- return Promise.reject(new Error('Tool calls not supported in this environment'));
1776
- },
1777
-
1778
- requestDisplayMode: function(options) {
1779
- if (isOpenAI && window.openai && window.openai.requestDisplayMode) {
1780
- return window.openai.requestDisplayMode(options);
1781
- }
1782
- if (isExtApps) {
1783
- return this._sendRequest('ui/request-display-mode', options);
1784
- }
1785
- // Polyfill: just update local state
1786
- if (options && options.mode) {
1787
- hostContext.displayMode = options.mode;
1788
- contextChangeListeners.forEach(function(cb) {
1789
- try { cb({ displayMode: options.mode }); } catch (e) {}
1790
- });
1791
- }
1792
- return Promise.resolve();
1793
- },
1794
-
1795
- requestClose: function() {
1796
- if (isOpenAI && window.openai && window.openai.requestClose) {
1797
- return window.openai.requestClose();
1798
- }
1799
- if (isExtApps) {
1800
- return this._sendRequest('ui/request-close', {});
1801
- }
1802
- // Polyfill: dispatch event for parent to handle
1803
- window.dispatchEvent(new CustomEvent('mcp:request-close'));
1804
- return Promise.resolve();
1805
- },
1806
-
1807
- openExternal: function(options) {
1808
- var href = typeof options === 'string' ? options : (options && options.href);
1809
- if (!href) {
1810
- return Promise.reject(new Error('URL required'));
1811
- }
1812
- if (isOpenAI && window.openai && window.openai.openExternal) {
1813
- return window.openai.openExternal({ href: href });
1814
- }
1815
- if (isExtApps) {
1816
- return this._sendRequest('ui/open-link', { url: href });
1817
- }
1818
- // Fallback: open in new window
1819
- window.open(href, '_blank', 'noopener,noreferrer');
1820
- return Promise.resolve();
1821
- },
1822
-
1823
- // Alias for openExternal (backwards compatibility)
1824
- openLink: function(url) {
1825
- return this.openExternal({ href: url });
1826
- },
1827
-
1828
- sendFollowUpMessage: function(options) {
1829
- var prompt = typeof options === 'string' ? options : (options && options.prompt);
1830
- if (!prompt) {
1831
- return Promise.reject(new Error('Prompt required'));
1832
- }
1833
- if (isOpenAI && window.openai && window.openai.sendFollowUpMessage) {
1834
- return window.openai.sendFollowUpMessage({ prompt: prompt });
1835
- }
1836
- if (isClaude) {
1837
- return Promise.reject(new Error(
1838
- 'Follow-up messages are not supported in Claude widgets (network-blocked sandbox)'
1839
- ));
1840
- }
1841
- if (isGemini) {
1842
- return Promise.reject(new Error(
1843
- 'Follow-up messages are not supported in Gemini widgets'
1844
- ));
1845
- }
1846
- if (isExtApps) {
1847
- return this._sendRequest('ui/message', {
1848
- role: 'user',
1849
- content: { type: 'text', text: prompt }
1850
- });
1851
- }
1852
- return Promise.reject(new Error('Messages not supported in this environment'));
1853
- },
1854
-
1855
- // Alias for sendFollowUpMessage (backwards compatibility)
1856
- sendMessage: function(content) {
1857
- return this.sendFollowUpMessage({ prompt: content });
1858
- },
1859
-
1860
- setWidgetState: function(state) {
1861
- if (isOpenAI && window.openai && window.openai.setWidgetState) {
1862
- window.openai.setWidgetState(state);
1863
- return;
1864
- }
1865
- // Polyfill: persist to localStorage
1866
- try {
1867
- localStorage.setItem('__mcpWidgetState', JSON.stringify(state));
1868
- } catch (e) {
1869
- console.warn('Failed to persist widget state:', e);
1870
- }
1871
- },
1872
-
1873
- // ==================== Context API (MCP-specific) ====================
1874
-
1875
- get context() {
1876
- return {
1877
- theme: this.theme,
1878
- displayMode: this.displayMode,
1879
- viewport: this.maxHeight ? { maxHeight: this.maxHeight } : undefined,
1880
- userAgent: this.userAgent,
1881
- locale: this.locale,
1882
- safeArea: this.safeArea
1883
- };
1884
- },
1885
-
1886
- onContextChange: function(callback) {
1887
- contextChangeListeners.push(callback);
1888
- return function() {
1889
- var index = contextChangeListeners.indexOf(callback);
1890
- if (index > -1) contextChangeListeners.splice(index, 1);
1891
- };
1892
- },
1893
-
1894
- onToolResult: function(callback) {
1895
- toolResultListeners.push(callback);
1896
- return function() {
1897
- var index = toolResultListeners.indexOf(callback);
1898
- if (index > -1) toolResultListeners.splice(index, 1);
1899
- };
1900
- },
1901
-
1902
- // ==================== Internal Methods ====================
1903
-
1904
- _sendRequest: function(method, params) {
1905
- return new Promise(function(resolve, reject) {
1906
- var id = ++messageId;
1907
- pendingRequests.set(id, { resolve: resolve, reject: reject });
1908
-
1909
- window.parent.postMessage({
1910
- jsonrpc: '2.0',
1911
- id: id,
1912
- method: method,
1913
- params: params
1914
- }, '*');
1915
-
1916
- // Timeout after 30s
1917
- setTimeout(function() {
1918
- if (pendingRequests.has(id)) {
1919
- pendingRequests.delete(id);
1920
- reject(new Error('Request timeout'));
1921
- }
1922
- }, 30000);
1923
- });
1924
- },
1925
-
1926
- _initExtApps: function() {
1927
- var self = this;
1928
- return this._sendRequest('ui/initialize', {}).then(function(result) {
1929
- if (result && result.hostContext) {
1930
- hostContext = Object.assign(hostContext, result.hostContext);
1931
- }
1932
- // Note: trustedOrigin is now set from first message event origin (trust-on-first-use)
1933
- // Send initialized notification
1934
- window.parent.postMessage({
1935
- jsonrpc: '2.0',
1936
- method: 'ui/notifications/initialized',
1937
- params: {}
1938
- }, '*');
1939
- return result;
1940
- });
1941
- }
1942
- };
1943
-
1944
- // ==================== Event Handling ====================
1945
-
1946
- window.addEventListener('message', function(event) {
1947
- var data = event.data;
1948
- if (!data || data.jsonrpc !== '2.0') return;
1949
-
1950
- // Trust-on-first-use: Establish trusted origin from the first valid message
1951
- if (isExtApps && !trustedOrigin && event.origin) {
1952
- trustedOrigin = event.origin;
1953
- }
1954
-
1955
- // Validate origin for ext-apps environment to prevent spoofed messages
1956
- if (isExtApps && trustedOrigin && event.origin !== trustedOrigin) {
1957
- console.warn('MCP Bridge: Ignoring message from untrusted origin:', event.origin);
1958
- return;
1959
- }
1960
-
1961
- // Handle responses
1962
- if (data.id && pendingRequests.has(data.id)) {
1963
- var pending = pendingRequests.get(data.id);
1964
- pendingRequests.delete(data.id);
1965
-
1966
- if (data.error) {
1967
- var err = new Error(data.error.message || 'Unknown error');
1968
- err.code = data.error.code;
1969
- err.data = data.error.data;
1970
- pending.reject(err);
1971
- } else {
1972
- pending.resolve(data.result);
1973
- }
1974
- return;
1975
- }
1976
-
1977
- // Handle notifications
1978
- switch (data.method) {
1979
- case 'ui/notifications/tool-input':
1980
- window.__mcpToolInput = data.params && data.params.arguments;
1981
- window.dispatchEvent(new CustomEvent('mcp:tool-input', { detail: data.params }));
1982
- break;
1983
-
1984
- case 'ui/notifications/tool-input-partial':
1985
- if (data.params && data.params.arguments) {
1986
- window.__mcpToolInput = Object.assign(window.__mcpToolInput || {}, data.params.arguments);
1987
- }
1988
- break;
1989
-
1990
- case 'ui/notifications/tool-result':
1991
- window.__mcpToolOutput = data.params && data.params.content;
1992
- window.__mcpStructuredContent = data.params && data.params.structuredContent;
1993
- toolResultListeners.forEach(function(cb) {
1994
- try { cb(data.params); } catch (e) { console.error('Tool result listener error:', e); }
1995
- });
1996
- window.dispatchEvent(new CustomEvent('mcp:tool-result', { detail: data.params }));
1997
- break;
1998
-
1999
- case 'ui/notifications/tool-cancelled':
2000
- window.dispatchEvent(new CustomEvent('mcp:tool-cancelled', { detail: data.params }));
2001
- break;
2002
-
2003
- case 'ui/host-context-change':
2004
- hostContext = Object.assign(hostContext, data.params);
2005
- contextChangeListeners.forEach(function(cb) {
2006
- try { cb(data.params); } catch (e) { console.error('Context change listener error:', e); }
2007
- });
2008
- window.dispatchEvent(new CustomEvent('mcp:context-change', { detail: data.params }));
2009
- break;
2010
-
2011
- case 'ui/size-change':
2012
- if (hostContext.viewport) {
2013
- hostContext.viewport = Object.assign(hostContext.viewport, data.params);
2014
- } else {
2015
- hostContext.viewport = data.params;
2016
- }
2017
- break;
2018
- }
2019
- });
2020
-
2021
- // ==================== Initialize ====================
2022
-
2023
- // Export bridge
2024
- window.mcpBridge = bridge;
2025
-
2026
- // Also create window.openai polyfill for non-OpenAI platforms
2027
- // This allows code written for OpenAI to work on other platforms
2028
- if (!isOpenAI) {
2029
- window.openai = {
2030
- get theme() { return bridge.theme; },
2031
- get userAgent() { return bridge.userAgent; },
2032
- get locale() { return bridge.locale; },
2033
- get maxHeight() { return bridge.maxHeight; },
2034
- get displayMode() { return bridge.displayMode; },
2035
- get safeArea() { return bridge.safeArea; },
2036
- get toolInput() { return bridge.toolInput; },
2037
- get toolOutput() { return bridge.toolOutput; },
2038
- get toolResponseMetadata() { return bridge.toolResponseMetadata; },
2039
- get widgetState() { return bridge.widgetState; },
2040
- callTool: function(n, a) { return bridge.callTool(n, a); },
2041
- requestDisplayMode: function(o) { return bridge.requestDisplayMode(o); },
2042
- requestClose: function() { return bridge.requestClose(); },
2043
- openExternal: function(o) { return bridge.openExternal(o); },
2044
- sendFollowUpMessage: function(o) { return bridge.sendFollowUpMessage(o); },
2045
- setWidgetState: function(s) { return bridge.setWidgetState(s); }
2046
- };
2047
- }
2048
-
2049
- // Auto-initialize for ext-apps
2050
- if (isExtApps) {
2051
- bridge._initExtApps().catch(function(err) {
2052
- console.warn('Failed to initialize MCP bridge:', err);
2053
- });
2054
- }
2055
-
2056
- // Dispatch ready event
2057
- window.dispatchEvent(new CustomEvent('mcp:bridge-ready'));
2058
- })();
2059
- </script>
2060
- `;
2061
- var FRONTMCP_BRIDGE_RUNTIME = BRIDGE_SCRIPT_TAGS.universal;
2062
-
2063
- // libs/uipack/src/runtime/csp.ts
2064
- var DEFAULT_CDN_DOMAINS = [
2065
- "https://cdn.jsdelivr.net",
2066
- // Tailwind, Alpine, React, icons
2067
- "https://cdnjs.cloudflare.com",
2068
- // HTMX, other libraries
2069
- "https://fonts.googleapis.com",
2070
- // Google Fonts stylesheets
2071
- "https://fonts.gstatic.com"
2072
- // Google Fonts files
2073
- ];
2074
- var DEFAULT_CSP_DIRECTIVES = [
2075
- "default-src 'none'",
2076
- `script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2077
- `style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2078
- `img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2079
- `font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2080
- "connect-src 'none'"
2081
- ];
2082
- function buildCSPDirectives(csp) {
2083
- if (!csp) {
2084
- return [...DEFAULT_CSP_DIRECTIVES];
2085
- }
2086
- const validResourceDomains = sanitizeCSPDomains(csp.resourceDomains);
2087
- const validConnectDomains = sanitizeCSPDomains(csp.connectDomains);
2088
- const allResourceDomains = [.../* @__PURE__ */ new Set([...DEFAULT_CDN_DOMAINS, ...validResourceDomains])];
2089
- const directives = [
2090
- "default-src 'none'",
2091
- `script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,
2092
- `style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`
2093
- ];
2094
- const imgSources = ["'self'", "data:", ...allResourceDomains];
2095
- directives.push(`img-src ${imgSources.join(" ")}`);
2096
- const fontSources = ["'self'", "data:", ...allResourceDomains];
2097
- directives.push(`font-src ${fontSources.join(" ")}`);
2098
- if (validConnectDomains.length) {
2099
- directives.push(`connect-src ${validConnectDomains.join(" ")}`);
2100
- } else {
2101
- directives.push("connect-src 'none'");
2102
- }
2103
- return directives;
2104
- }
2105
- function buildCSPMetaTag(csp) {
2106
- const directives = buildCSPDirectives(csp);
2107
- const content = directives.join("; ");
2108
- return `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`;
2109
- }
2110
- function escapeAttribute(str) {
2111
- return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2112
- }
2113
- function validateCSPDomain(domain) {
2114
- if (domain.startsWith("https://*.")) {
2115
- const rest = domain.slice(10);
2116
- return /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.[a-zA-Z]{2,}$/.test(rest);
2117
- }
2118
- try {
2119
- const url = new URL(domain);
2120
- return url.protocol === "https:";
2121
- } catch {
2122
- return false;
2123
- }
2124
- }
2125
- function sanitizeCSPDomains(domains) {
2126
- if (!domains) return [];
2127
- const valid = [];
2128
- for (const domain of domains) {
2129
- if (validateCSPDomain(domain)) {
2130
- valid.push(domain);
2131
- } else {
2132
- console.warn(`Invalid CSP domain ignored: ${domain}`);
2133
- }
2134
- }
2135
- return valid;
2136
- }
2137
-
2138
- // libs/uipack/src/theme/cdn.ts
2139
- var CDN = {
2140
- /**
2141
- * Tailwind CSS v4 Browser CDN
2142
- * Generates styles on-the-fly with @theme support
2143
- * @see https://tailwindcss.com/docs/installation/play-cdn
2144
- */
2145
- tailwind: "https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",
2146
- /**
2147
- * HTMX 2.x - High power tools for HTML
2148
- * Enables AJAX, WebSockets, Server Sent Events directly in HTML
2149
- * @see https://htmx.org
2150
- */
2151
- htmx: {
2152
- url: "https://cdnjs.cloudflare.com/ajax/libs/htmx/2.0.7/htmx.min.js",
2153
- integrity: "sha512-T6VLg/MJYMbLTmQ8VLvonbWg8VOvmDhXcOvHzCwo6ShdGuUU5SEcp1IAPXL4k9lVoMi8gRXl5K/S/zh43Y9rJA=="
2154
- },
2155
- /**
2156
- * Alpine.js - Lightweight reactive framework
2157
- * Used for more complex client-side interactions
2158
- * @see https://alpinejs.dev
2159
- */
2160
- alpine: {
2161
- url: "https://cdn.jsdelivr.net/npm/alpinejs@3.14.3/dist/cdn.min.js",
2162
- integrity: "sha384-6zY8MFQJ/EqS1r4RJl+7j8rvZPuBWpT0RzWf+IFcKhxqUzQNmJzA1X1VEVZhYaEz"
2163
- },
2164
- /**
2165
- * Google Fonts - Inter for modern UI typography
2166
- */
2167
- fonts: {
2168
- preconnect: ["https://fonts.googleapis.com", "https://fonts.gstatic.com"],
2169
- inter: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap",
2170
- mono: "https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap"
2171
- },
2172
- /**
2173
- * Lucide Icons - Beautiful & consistent icons
2174
- * @see https://lucide.dev
2175
- */
2176
- icons: {
2177
- url: "https://cdn.jsdelivr.net/npm/lucide@0.294.0/dist/umd/lucide.min.js",
2178
- integrity: "sha384-wpLmHb7v7V1LsEuTmPQ9tXqWZvTtRWWVqJuE+Yz6X0I6O2T6bHJVeXH1lVWqF4qE"
2179
- }
2180
- };
2181
- var scriptCache = /* @__PURE__ */ new Map();
2182
- function getCachedScript(url) {
2183
- return scriptCache.get(url);
2184
- }
2185
- function buildFontPreconnect() {
2186
- return CDN.fonts.preconnect.map((url, i) => `<link rel="preconnect" href="${url}"${i > 0 ? " crossorigin" : ""}>`).join("\n ");
2187
- }
2188
- function buildFontStylesheets(options = {}) {
2189
- const { inter = true, mono = false } = options;
2190
- const links = [];
2191
- if (inter) {
2192
- links.push(`<link href="${CDN.fonts.inter}" rel="stylesheet">`);
2193
- }
2194
- if (mono) {
2195
- links.push(`<link href="${CDN.fonts.mono}" rel="stylesheet">`);
2196
- }
2197
- return links.join("\n ");
2198
- }
2199
- function buildScriptTag(url, integrity, options = {}) {
2200
- const attrs = [`src="${url}"`];
2201
- if (integrity) {
2202
- attrs.push(`integrity="${integrity}"`);
2203
- attrs.push('crossorigin="anonymous"');
2204
- }
2205
- if (options.defer) attrs.push("defer");
2206
- if (options.async) attrs.push("async");
2207
- return `<script ${attrs.join(" ")}></script>`;
2208
- }
2209
- function buildInlineScriptTag(content) {
2210
- return `<script>${content}</script>`;
2211
- }
2212
- function buildCdnScripts(options = {}) {
2213
- const { tailwind = true, htmx = true, alpine = false, icons = false, inline = false } = options;
2214
- const scripts = [];
2215
- if (inline) {
2216
- if (tailwind) {
2217
- const cached = getCachedScript(CDN.tailwind);
2218
- if (cached) {
2219
- scripts.push(buildInlineScriptTag(cached));
2220
- } else {
2221
- console.warn(
2222
- "[frontmcp/ui] Inline mode requested but Tailwind script not cached. Call fetchAndCacheScripts() first."
2223
- );
2224
- }
2225
- }
2226
- if (htmx) {
2227
- const cached = getCachedScript(CDN.htmx.url);
2228
- if (cached) {
2229
- scripts.push(buildInlineScriptTag(cached));
2230
- } else {
2231
- console.warn(
2232
- "[frontmcp/ui] Inline mode requested but HTMX script not cached. Call fetchAndCacheScripts() first."
2233
- );
2234
- }
2235
- }
2236
- if (alpine) {
2237
- const cached = getCachedScript(CDN.alpine.url);
2238
- if (cached) {
2239
- scripts.push(buildInlineScriptTag(cached));
2240
- } else {
2241
- console.warn(
2242
- "[frontmcp/ui] Inline mode requested but Alpine.js script not cached. Call fetchAndCacheScripts() first."
2243
- );
2244
- }
2245
- }
2246
- if (icons) {
2247
- const cached = getCachedScript(CDN.icons.url);
2248
- if (cached) {
2249
- scripts.push(buildInlineScriptTag(cached));
2250
- } else {
2251
- console.warn(
2252
- "[frontmcp/ui] Inline mode requested but Lucide icons script not cached. Call fetchAndCacheScripts() first."
2253
- );
2254
- }
2255
- }
2256
- } else {
2257
- if (tailwind) {
2258
- scripts.push(buildScriptTag(CDN.tailwind));
2259
- }
2260
- if (htmx) {
2261
- scripts.push(buildScriptTag(CDN.htmx.url, CDN.htmx.integrity));
2262
- }
2263
- if (alpine) {
2264
- scripts.push(buildScriptTag(CDN.alpine.url, CDN.alpine.integrity, { defer: true }));
2265
- }
2266
- if (icons) {
2267
- scripts.push(buildScriptTag(CDN.icons.url, CDN.icons.integrity));
2268
- }
2269
- }
2270
- return scripts.join("\n ");
2271
- }
2272
-
2273
- // libs/uipack/src/theme/platforms.ts
2274
- var OPENAI_PLATFORM = {
2275
- id: "openai",
2276
- name: "OpenAI",
2277
- supportsWidgets: true,
2278
- supportsTailwind: true,
2279
- supportsHtmx: true,
2280
- networkMode: "full",
2281
- scriptStrategy: "cdn",
2282
- options: {
2283
- sdk: "apps-sdk",
2284
- version: "1.0"
2285
- }
2286
- };
2287
- var CLAUDE_PLATFORM = {
2288
- id: "claude",
2289
- name: "Claude (Artifacts)",
2290
- supportsWidgets: true,
2291
- // Claude Artifacts support interactive widgets
2292
- supportsTailwind: true,
2293
- supportsHtmx: false,
2294
- // Network blocked, HTMX won't work for API calls
2295
- networkMode: "limited",
2296
- scriptStrategy: "cdn",
2297
- maxInlineSize: 100 * 1024,
2298
- // 100KB limit for artifacts
2299
- cspRestrictions: ["script-src 'unsafe-inline'", "connect-src 'none'"],
2300
- options: {
2301
- mode: "artifacts",
2302
- framework: "react"
2303
- // Claude artifacts prefer React
2304
- }
2305
- };
2306
- function canUseCdn(platform) {
2307
- return platform.networkMode === "full" && platform.scriptStrategy === "cdn";
2308
- }
2309
- function needsInlineScripts(platform) {
2310
- return platform.scriptStrategy === "inline" || platform.networkMode === "blocked";
2311
- }
2312
-
2313
- // libs/uipack/src/theme/presets/github-openai.ts
2314
- var GITHUB_OPENAI_THEME = {
2315
- name: "github-openai",
2316
- colors: {
2317
- semantic: {
2318
- // Primary: Near-black for main actions and branding
2319
- primary: "#24292f",
2320
- // Secondary: Medium gray for secondary elements
2321
- secondary: "#57606a",
2322
- // Accent: Blue for links, focus states, and highlights
2323
- accent: "#0969da",
2324
- // Status colors
2325
- success: "#1a7f37",
2326
- // GitHub green
2327
- warning: "#9a6700",
2328
- // Amber warning
2329
- danger: "#cf222e",
2330
- // GitHub red
2331
- info: "#0969da"
2332
- // Blue info
2333
- },
2334
- surface: {
2335
- // Pure white background
2336
- background: "#ffffff",
2337
- // Light gray surface (GitHub code background style)
2338
- surface: "#f6f8fa",
2339
- // White elevated surfaces (modals, cards)
2340
- elevated: "#ffffff",
2341
- // Dark semi-transparent overlay
2342
- overlay: "rgba(27, 31, 36, 0.5)"
2343
- },
2344
- text: {
2345
- // Near-black for primary text
2346
- primary: "#24292f",
2347
- // Gray for secondary/muted text
2348
- secondary: "#57606a",
2349
- // Light gray for disabled text
2350
- disabled: "#8c959f",
2351
- // White for text on dark backgrounds
2352
- inverse: "#ffffff",
2353
- // Blue for links
2354
- link: "#0969da"
2355
- },
2356
- border: {
2357
- // Light gray border (GitHub style)
2358
- default: "#d0d7de",
2359
- // Medium gray on hover
2360
- hover: "#8c959f",
2361
- // Blue focus ring
2362
- focus: "#0969da",
2363
- // Subtle divider
2364
- divider: "#d8dee4"
2365
- }
2366
- },
2367
- typography: {
2368
- families: {
2369
- // System UI font stack (GitHub/Apple style)
2370
- sans: '-apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"',
2371
- // Monospace stack
2372
- mono: 'ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, "Liberation Mono", monospace'
2373
- },
2374
- sizes: {
2375
- xs: "0.75rem",
2376
- // 12px
2377
- sm: "0.875rem",
2378
- // 14px
2379
- base: "1rem",
2380
- // 16px
2381
- lg: "1.125rem",
2382
- // 18px
2383
- xl: "1.25rem",
2384
- // 20px
2385
- "2xl": "1.5rem",
2386
- // 24px
2387
- "3xl": "1.875rem",
2388
- // 30px
2389
- "4xl": "2.25rem"
2390
- // 36px
2391
- },
2392
- weights: {
2393
- normal: "400",
2394
- medium: "500",
2395
- semibold: "600",
2396
- bold: "700"
2397
- }
2398
- },
2399
- radius: {
2400
- none: "0",
2401
- sm: "3px",
2402
- // GitHub uses smaller radii
2403
- md: "6px",
2404
- lg: "8px",
2405
- xl: "12px",
2406
- "2xl": "16px",
2407
- full: "9999px"
2408
- },
2409
- shadows: {
2410
- // Subtle shadows with gray tones
2411
- sm: "0 1px 0 rgba(27, 31, 36, 0.04)",
2412
- md: "0 3px 6px rgba(140, 149, 159, 0.15)",
2413
- lg: "0 8px 24px rgba(140, 149, 159, 0.2)",
2414
- xl: "0 12px 28px rgba(140, 149, 159, 0.3)"
2415
- },
2416
- components: {
2417
- button: {
2418
- radius: "6px",
2419
- paddingX: "16px",
2420
- paddingY: "5px",
2421
- fontSize: "14px",
2422
- fontWeight: "500"
2423
- },
2424
- card: {
2425
- radius: "6px",
2426
- padding: "16px",
2427
- shadow: "0 1px 0 rgba(27, 31, 36, 0.04)",
2428
- borderWidth: "1px"
2429
- },
2430
- input: {
2431
- radius: "6px",
2432
- paddingX: "12px",
2433
- paddingY: "5px",
2434
- borderWidth: "1px",
2435
- focusRingWidth: "3px"
2436
- }
2437
- },
2438
- cdn: {
2439
- fonts: {
2440
- preconnect: ["https://fonts.googleapis.com", "https://fonts.gstatic.com"],
2441
- stylesheets: [
2442
- // System UI fonts don't need external stylesheets, but we include
2443
- // Inter as an optional enhancement for consistent cross-platform rendering
2444
- "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
2445
- ]
2446
- },
2447
- icons: {
2448
- script: {
2449
- url: "https://cdn.jsdelivr.net/npm/lucide@0.294.0/dist/umd/lucide.min.js"
2450
- }
2451
- },
2452
- scripts: {
2453
- tailwind: "https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4",
2454
- htmx: {
2455
- url: "https://cdnjs.cloudflare.com/ajax/libs/htmx/2.0.7/htmx.min.js",
2456
- integrity: "sha512-T6VLg/MJYMbLTmQ8VLvonbWg8VOvmDhXcOvHzCwo6ShdGuUU5SEcp1IAPXL4k9lVoMi8gRXl5K/S/zh43Y9rJA=="
2457
- },
2458
- alpine: {
2459
- url: "https://cdn.jsdelivr.net/npm/alpinejs@3.14.3/dist/cdn.min.js",
2460
- integrity: "sha384-6zY8MFQJ/EqS1r4RJl+7j8rvZPuBWpT0RzWf+IFcKhxqUzQNmJzA1X1VEVZhYaEz"
2461
- }
2462
- }
2463
- }
2464
- };
2465
- var DEFAULT_THEME = GITHUB_OPENAI_THEME;
2466
-
2467
- // libs/uipack/src/theme/theme.ts
2468
- function mergeThemesCore(base, override) {
2469
- const baseColors = base.colors ?? { semantic: { primary: "#24292f" } };
2470
- const filterStrings = (arr) => arr.filter((s) => s !== void 0);
2471
- return {
2472
- ...base,
2473
- ...override,
2474
- colors: {
2475
- ...baseColors,
2476
- ...override.colors,
2477
- semantic: { ...baseColors.semantic, ...override.colors?.semantic },
2478
- surface: { ...baseColors.surface, ...override.colors?.surface },
2479
- text: { ...baseColors.text, ...override.colors?.text },
2480
- border: { ...baseColors.border, ...override.colors?.border },
2481
- custom: { ...baseColors.custom, ...override.colors?.custom }
2482
- },
2483
- typography: {
2484
- ...base.typography,
2485
- ...override.typography,
2486
- families: { ...base.typography?.families, ...override.typography?.families },
2487
- sizes: { ...base.typography?.sizes, ...override.typography?.sizes },
2488
- weights: { ...base.typography?.weights, ...override.typography?.weights },
2489
- lineHeight: { ...base.typography?.lineHeight, ...override.typography?.lineHeight }
2490
- },
2491
- spacing: { ...base.spacing, ...override.spacing },
2492
- radius: { ...base.radius, ...override.radius },
2493
- shadows: { ...base.shadows, ...override.shadows },
2494
- components: {
2495
- ...base.components,
2496
- ...override.components,
2497
- button: { ...base.components?.button, ...override.components?.button },
2498
- card: { ...base.components?.card, ...override.components?.card },
2499
- input: { ...base.components?.input, ...override.components?.input }
2500
- },
2501
- cdn: {
2502
- ...base.cdn,
2503
- ...override.cdn,
2504
- fonts: {
2505
- // Concatenate then dedupe so base entries are preserved without duplicates
2506
- preconnect: filterStrings(
2507
- Array.from(/* @__PURE__ */ new Set([...base.cdn?.fonts?.preconnect ?? [], ...override.cdn?.fonts?.preconnect ?? []]))
2508
- ),
2509
- stylesheets: filterStrings(
2510
- Array.from(/* @__PURE__ */ new Set([...base.cdn?.fonts?.stylesheets ?? [], ...override.cdn?.fonts?.stylesheets ?? []]))
2511
- )
2512
- },
2513
- icons: {
2514
- ...base.cdn?.icons,
2515
- ...override.cdn?.icons,
2516
- // Deep merge script to preserve integrity when only url is overridden
2517
- script: override.cdn?.icons?.script ? { ...base.cdn?.icons?.script, ...override.cdn?.icons?.script } : base.cdn?.icons?.script
2518
- },
2519
- scripts: {
2520
- // tailwind is a simple string, just use override or base
2521
- tailwind: override.cdn?.scripts?.tailwind ?? base.cdn?.scripts?.tailwind,
2522
- // Deep merge htmx/alpine to preserve integrity when only url is overridden
2523
- htmx: override.cdn?.scripts?.htmx ? { ...base.cdn?.scripts?.htmx, ...override.cdn?.scripts?.htmx } : base.cdn?.scripts?.htmx,
2524
- alpine: override.cdn?.scripts?.alpine ? { ...base.cdn?.scripts?.alpine, ...override.cdn?.scripts?.alpine } : base.cdn?.scripts?.alpine
2525
- }
2526
- },
2527
- customVars: { ...base.customVars, ...override.customVars },
2528
- customCss: [base.customCss, override.customCss].filter(Boolean).join("\n")
2529
- };
2530
- }
2531
- function mergeThemes(base, override) {
2532
- const merged = mergeThemesCore(base, override);
2533
- let darkVariant;
2534
- if (override.dark !== void 0) {
2535
- const darkBase = base.dark ?? base;
2536
- const { dark: _nestedDark, ...overrideDarkWithoutNested } = override.dark;
2537
- darkVariant = mergeThemesCore(darkBase, overrideDarkWithoutNested);
2538
- } else if (base.dark !== void 0) {
2539
- const { dark: _nestedDark, ...baseDarkWithoutNested } = base.dark;
2540
- darkVariant = baseDarkWithoutNested;
2541
- }
2542
- return {
2543
- ...merged,
2544
- dark: darkVariant
2545
- };
2546
- }
2547
- function emitColorScale(lines, name, scale) {
2548
- for (const [shade, value] of Object.entries(scale)) {
2549
- if (value) lines.push(`--color-${name}-${shade}: ${value};`);
2550
- }
2551
- }
2552
- var OPACITY_VARIANTS = [10, 20, 30, 50, 70, 90];
2553
- function emitColorWithOpacityVariants(lines, name, value) {
2554
- lines.push(`--color-${name}: ${value};`);
2555
- for (const opacity of OPACITY_VARIANTS) {
2556
- lines.push(`--color-${name}-${opacity}: color-mix(in oklch, ${value} ${opacity}%, transparent);`);
2557
- }
2558
- }
2559
- function emitBrandColorWithVariants(lines, name, value) {
2560
- lines.push(`--color-${name}: ${value};`);
2561
- lines.push(`--color-${name}-hover: color-mix(in oklch, ${value} 85%, black);`);
2562
- for (const opacity of OPACITY_VARIANTS) {
2563
- lines.push(`--color-${name}-${opacity}: color-mix(in oklch, ${value} ${opacity}%, transparent);`);
2564
- }
2565
- }
2566
- function buildThemeCss(theme) {
2567
- const lines = [];
2568
- const semantic = theme.colors.semantic;
2569
- if (typeof semantic.primary === "string") {
2570
- emitBrandColorWithVariants(lines, "primary", semantic.primary);
2571
- } else if (semantic.primary) {
2572
- emitColorScale(lines, "primary", semantic.primary);
2573
- }
2574
- if (semantic.secondary) {
2575
- if (typeof semantic.secondary === "string") {
2576
- emitBrandColorWithVariants(lines, "secondary", semantic.secondary);
2577
- } else {
2578
- emitColorScale(lines, "secondary", semantic.secondary);
2579
- }
2580
- }
2581
- if (semantic.accent) {
2582
- if (typeof semantic.accent === "string") {
2583
- lines.push(`--color-accent: ${semantic.accent};`);
2584
- } else {
2585
- emitColorScale(lines, "accent", semantic.accent);
2586
- }
2587
- }
2588
- if (semantic.neutral) {
2589
- if (typeof semantic.neutral === "string") {
2590
- lines.push(`--color-neutral: ${semantic.neutral};`);
2591
- } else {
2592
- emitColorScale(lines, "neutral", semantic.neutral);
2593
- }
2594
- }
2595
- if (semantic.success) emitColorWithOpacityVariants(lines, "success", semantic.success);
2596
- if (semantic.warning) emitColorWithOpacityVariants(lines, "warning", semantic.warning);
2597
- if (semantic.danger) emitColorWithOpacityVariants(lines, "danger", semantic.danger);
2598
- if (semantic.info) emitColorWithOpacityVariants(lines, "info", semantic.info);
2599
- const surface = theme.colors.surface;
2600
- if (surface?.background) lines.push(`--color-background: ${surface.background};`);
2601
- if (surface?.surface) lines.push(`--color-surface: ${surface.surface};`);
2602
- if (surface?.elevated) lines.push(`--color-elevated: ${surface.elevated};`);
2603
- if (surface?.overlay) lines.push(`--color-overlay: ${surface.overlay};`);
2604
- const text = theme.colors.text;
2605
- if (text?.primary) lines.push(`--color-text-primary: ${text.primary};`);
2606
- if (text?.secondary) lines.push(`--color-text-secondary: ${text.secondary};`);
2607
- if (text?.disabled) lines.push(`--color-text-disabled: ${text.disabled};`);
2608
- if (text?.inverse) lines.push(`--color-text-inverse: ${text.inverse};`);
2609
- if (text?.link) lines.push(`--color-text-link: ${text.link};`);
2610
- const border = theme.colors.border;
2611
- if (border?.default) lines.push(`--color-border: ${border.default};`);
2612
- if (border?.hover) lines.push(`--color-border-hover: ${border.hover};`);
2613
- if (border?.focus) lines.push(`--color-border-focus: ${border.focus};`);
2614
- if (border?.divider) lines.push(`--color-divider: ${border.divider};`);
2615
- if (theme.colors.custom) {
2616
- for (const [key, value] of Object.entries(theme.colors.custom)) {
2617
- lines.push(`--color-${key}: ${value};`);
2618
- }
2619
- }
2620
- const typography = theme.typography;
2621
- if (typography?.families?.sans) lines.push(`--font-sans: ${typography.families.sans};`);
2622
- if (typography?.families?.serif) lines.push(`--font-serif: ${typography.families.serif};`);
2623
- if (typography?.families?.mono) lines.push(`--font-mono: ${typography.families.mono};`);
2624
- if (typography?.families?.display) lines.push(`--font-display: ${typography.families.display};`);
2625
- const radius = theme.radius;
2626
- if (radius?.none) lines.push(`--radius-none: ${radius.none};`);
2627
- if (radius?.sm) lines.push(`--radius-sm: ${radius.sm};`);
2628
- if (radius?.md) lines.push(`--radius-md: ${radius.md};`);
2629
- if (radius?.lg) lines.push(`--radius-lg: ${radius.lg};`);
2630
- if (radius?.xl) lines.push(`--radius-xl: ${radius.xl};`);
2631
- if (radius?.["2xl"]) lines.push(`--radius-2xl: ${radius["2xl"]};`);
2632
- if (radius?.full) lines.push(`--radius-full: ${radius.full};`);
2633
- if (theme.customVars) {
2634
- for (const [key, value] of Object.entries(theme.customVars)) {
2635
- lines.push(`${key}: ${value};`);
2636
- }
2637
- }
2638
- return lines.join("\n ");
2639
- }
2640
-
2641
- // libs/uipack/src/runtime/wrapper.ts
2642
- init_utils();
2643
-
2644
- // libs/uipack/src/runtime/sanitizer.ts
2645
- import DOMPurify from "dompurify";
2646
- var REDACTION_TOKENS = {
2647
- EMAIL: "[EMAIL]",
2648
- PHONE: "[PHONE]",
2649
- CARD: "[CARD]",
2650
- ID: "[ID]",
2651
- IP: "[IP]",
2652
- REDACTED: "[REDACTED]"
2653
- };
2654
- var PII_PATTERNS = {
2655
- // Email: user@domain.tld
2656
- email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
2657
- // Email embedded in text
2658
- emailInText: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
2659
- // Phone: Various formats (US-centric but flexible)
2660
- phone: /^[+]?[(]?[0-9]{1,4}[)]?[-\s.]?[0-9]{1,4}[-\s.]?[0-9]{1,9}$/,
2661
- // Phone embedded in text
2662
- phoneInText: /(?:\+?1[-.\s]?)?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}/g,
2663
- // Credit card: 13-19 digits (with optional separators)
2664
- creditCard: /^(?:[0-9]{4}[-\s]?){3,4}[0-9]{1,4}$/,
2665
- // Credit card embedded in text
2666
- creditCardInText: /\b(?:[0-9]{4}[-\s]?){3,4}[0-9]{1,4}\b/g,
2667
- // SSN: XXX-XX-XXXX
2668
- ssn: /^[0-9]{3}[-]?[0-9]{2}[-]?[0-9]{4}$/,
2669
- // SSN embedded in text
2670
- ssnInText: /\b[0-9]{3}[-]?[0-9]{2}[-]?[0-9]{4}\b/g,
2671
- // IPv4 address
2672
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
2673
- // IPv4 embedded in text
2674
- ipv4InText: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g
2675
- };
2676
- function isEmail(value) {
2677
- return PII_PATTERNS.email.test(value);
2678
- }
2679
- function isPhone(value) {
2680
- return PII_PATTERNS.phone.test(value);
2681
- }
2682
- function isCreditCard(value) {
2683
- const digits = value.replace(/[-\s]/g, "");
2684
- return digits.length >= 13 && digits.length <= 19 && PII_PATTERNS.creditCard.test(value);
2685
- }
2686
- function isSSN(value) {
2687
- return PII_PATTERNS.ssn.test(value);
2688
- }
2689
- function isIPv4(value) {
2690
- return PII_PATTERNS.ipv4.test(value);
2691
- }
2692
- function detectPIIType(value) {
2693
- if (isEmail(value)) return "EMAIL";
2694
- if (isCreditCard(value)) return "CARD";
2695
- if (isSSN(value)) return "ID";
2696
- if (isPhone(value)) return "PHONE";
2697
- if (isIPv4(value)) return "IP";
2698
- return null;
2699
- }
2700
- var MAX_PII_TEXT_LENGTH = 1e5;
2701
- function redactPIIFromText(text) {
2702
- if (text.length > MAX_PII_TEXT_LENGTH) {
2703
- return text;
2704
- }
2705
- let result = text;
2706
- result = result.replace(PII_PATTERNS.creditCardInText, REDACTION_TOKENS.CARD);
2707
- result = result.replace(PII_PATTERNS.ssnInText, REDACTION_TOKENS.ID);
2708
- result = result.replace(PII_PATTERNS.emailInText, REDACTION_TOKENS.EMAIL);
2709
- result = result.replace(PII_PATTERNS.phoneInText, REDACTION_TOKENS.PHONE);
2710
- result = result.replace(PII_PATTERNS.ipv4InText, REDACTION_TOKENS.IP);
2711
- return result;
2712
- }
2713
- function sanitizeValue(key, value, path, options, depth, visited) {
2714
- const maxDepth = options.maxDepth ?? 10;
2715
- if (depth > maxDepth) {
2716
- return value;
2717
- }
2718
- if (value === null || value === void 0) {
2719
- return value;
2720
- }
2721
- if (typeof options.mode === "function") {
2722
- return options.mode(key, value, path);
2723
- }
2724
- if (Array.isArray(options.mode)) {
2725
- const lowerKey = key.toLowerCase();
2726
- if (options.mode.some((f) => f.toLowerCase() === lowerKey)) {
2727
- return REDACTION_TOKENS.REDACTED;
2728
- }
2729
- }
2730
- if (typeof value === "string") {
2731
- if (options.mode === true) {
2732
- const piiType = detectPIIType(value);
2733
- if (piiType) {
2734
- return REDACTION_TOKENS[piiType];
2735
- }
2736
- if (options.sanitizeInText !== false) {
2737
- const redacted = redactPIIFromText(value);
2738
- if (redacted !== value) {
2739
- return redacted;
2740
- }
2741
- }
2742
- }
2743
- return value;
2744
- }
2745
- if (Array.isArray(value)) {
2746
- if (visited.has(value)) {
2747
- return REDACTION_TOKENS.REDACTED;
2748
- }
2749
- visited.add(value);
2750
- return value.map(
2751
- (item, index) => sanitizeValue(String(index), item, [...path, String(index)], options, depth + 1, visited)
2752
- );
2753
- }
2754
- if (typeof value === "object") {
2755
- if (visited.has(value)) {
2756
- return REDACTION_TOKENS.REDACTED;
2757
- }
2758
- visited.add(value);
2759
- const result = {};
2760
- for (const [k, v] of Object.entries(value)) {
2761
- result[k] = sanitizeValue(k, v, [...path, k], options, depth + 1, visited);
2762
- }
2763
- return result;
2764
- }
2765
- return value;
2766
- }
2767
- function sanitizeInput(input, mode = true) {
2768
- if (!input || typeof input !== "object") {
2769
- return {};
2770
- }
2771
- const options = {
2772
- mode,
2773
- maxDepth: 10,
2774
- sanitizeInText: true
2775
- };
2776
- const visited = /* @__PURE__ */ new WeakSet();
2777
- return sanitizeValue("", input, [], options, 0, visited);
2778
- }
2779
-
2780
- // libs/uipack/src/runtime/wrapper.ts
2781
- function createTemplateHelpers() {
2782
- let idCounter2 = 0;
2783
- return {
2784
- /**
2785
- * Escape HTML special characters to prevent XSS
2786
- */
2787
- escapeHtml,
2788
- /**
2789
- * Format a date for display
2790
- */
2791
- formatDate: (date, format) => {
2792
- const d = typeof date === "string" ? new Date(date) : date;
2793
- if (isNaN(d.getTime())) return String(date);
2794
- if (format === "iso") {
2795
- return d.toISOString();
2796
- }
2797
- if (format === "time") {
2798
- return d.toLocaleTimeString();
2799
- }
2800
- if (format === "datetime") {
2801
- return d.toLocaleString();
2802
- }
2803
- return d.toLocaleDateString();
2804
- },
2805
- /**
2806
- * Format a number as currency
2807
- */
2808
- formatCurrency: (amount, currency = "USD") => {
2809
- return new Intl.NumberFormat("en-US", {
2810
- style: "currency",
2811
- currency
2812
- }).format(amount);
2813
- },
2814
- /**
2815
- * Generate a unique ID for DOM elements
2816
- */
2817
- uniqueId: (prefix = "mcp") => {
2818
- return `${prefix}-${++idCounter2}-${Date.now().toString(36)}`;
2819
- },
2820
- /**
2821
- * Safely embed JSON data in HTML
2822
- * Escapes characters that could break out of script tags or HTML
2823
- */
2824
- jsonEmbed: (data) => {
2825
- const json2 = JSON.stringify(data);
2826
- if (json2 === void 0) {
2827
- return "undefined";
2828
- }
2829
- return json2.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026").replace(/'/g, "\\u0027");
2830
- }
2831
- };
2832
- }
2833
- function wrapToolUI(options) {
2834
- const {
2835
- content,
2836
- toolName,
2837
- input = {},
2838
- output,
2839
- structuredContent,
2840
- csp,
2841
- widgetAccessible = false,
2842
- title,
2843
- theme: themeOverrides,
2844
- platform = OPENAI_PLATFORM,
2845
- hostContext,
2846
- sanitizeInput: sanitizeOption,
2847
- rendererType,
2848
- hydrate = false,
2849
- // Disabled by default to prevent React hydration Error #418 in MCP clients
2850
- skipCspMeta = false
2851
- } = options;
2852
- let sanitizedInput = input;
2853
- if (sanitizeOption) {
2854
- const sanitizeMode = sanitizeOption === true ? true : sanitizeOption;
2855
- sanitizedInput = sanitizeInput(input, sanitizeMode);
2856
- }
2857
- const theme = themeOverrides ? mergeThemes(DEFAULT_THEME, themeOverrides) : DEFAULT_THEME;
2858
- const useCdn = canUseCdn(platform);
2859
- const useInline = needsInlineScripts(platform);
2860
- const fontPreconnect = useCdn ? buildFontPreconnect() : "";
2861
- const fontStylesheets = useCdn ? buildFontStylesheets({ inter: true }) : "";
2862
- const scripts = buildCdnScripts({
2863
- tailwind: platform.supportsTailwind,
2864
- htmx: false,
2865
- alpine: false,
2866
- icons: false,
2867
- inline: useInline
2868
- });
2869
- const frameworkScripts = buildFrameworkRuntimeScripts({
2870
- rendererType,
2871
- hydrate,
2872
- platform
2873
- });
2874
- const themeCss = buildThemeCss(theme);
2875
- const customCss = theme.customCss || "";
2876
- const styleBlock = platform.supportsTailwind ? `<style type="text/tailwindcss">
2877
- @theme {
2878
- ${themeCss}
2879
- }
2880
- ${customCss}
2881
- </style>` : "";
2882
- const cspMetaTag = skipCspMeta ? "" : buildCSPMetaTag(csp);
2883
- const dataScript = buildDataInjectionScript({
2884
- toolName,
2885
- input: sanitizedInput,
2886
- output,
2887
- structuredContent,
2888
- widgetAccessible,
2889
- hostContext
2890
- });
2891
- const pageTitle = title || `${escapeHtml(toolName)} - Tool Result`;
2892
- return `<!DOCTYPE html>
2893
- <html lang="en">
2894
- <head>
2895
- <meta charset="UTF-8">
2896
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
2897
- <title>${pageTitle}</title>
2898
- ${cspMetaTag}
2899
-
2900
- <!-- Fonts -->
2901
- ${fontPreconnect}
2902
- ${fontStylesheets}
2903
-
2904
- <!-- Tailwind CSS -->
2905
- ${scripts}
2906
- ${styleBlock}
2907
-
2908
- <!-- Framework Runtime -->
2909
- ${frameworkScripts}
2910
-
2911
- <!-- Tool Data -->
2912
- ${dataScript}
2913
-
2914
- <!-- MCP Bridge Runtime -->
2915
- ${MCP_BRIDGE_RUNTIME}
2916
- </head>
2917
- <body class="bg-background text-text-primary font-sans antialiased">
2918
- ${content}
2919
- </body>
2920
- </html>`;
2921
- }
2922
- function buildFrameworkRuntimeScripts(options) {
2923
- const { rendererType, hydrate, platform } = options;
2924
- if (!rendererType || rendererType === "html" || rendererType === "html-fallback") {
2925
- return "";
2926
- }
2927
- if (!hydrate) {
2928
- return "";
2929
- }
2930
- if (rendererType === "react" || rendererType === "mdx") {
2931
- const useCdn = canUseCdn(platform);
2932
- if (useCdn) {
2933
- return `
2934
- <!-- React Runtime (for hydration) -->
2935
- <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
2936
- <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
2937
- <script>
2938
- // Hydration script for React/MDX components
2939
- (function() {
2940
- document.addEventListener('DOMContentLoaded', function() {
2941
- var hydratables = document.querySelectorAll('[data-hydrate], [data-mdx-hydrate]');
2942
- if (hydratables.length > 0 && window.__frontmcp_components) {
2943
- hydratables.forEach(function(el) {
2944
- var componentName = el.getAttribute('data-hydrate');
2945
- var propsJson = el.getAttribute('data-props');
2946
- var props = propsJson ? JSON.parse(propsJson) : {};
2947
-
2948
- if (window.__frontmcp_components[componentName]) {
2949
- try {
2950
- ReactDOM.hydrateRoot(el, React.createElement(
2951
- window.__frontmcp_components[componentName],
2952
- props
2953
- ));
2954
- } catch (e) {
2955
- console.error('[FrontMCP] Hydration failed:', e);
2956
- }
2957
- }
2958
- });
2959
- }
2960
- });
2961
- })();
2962
- </script>`;
2963
- } else {
2964
- return `
2965
- <!-- React hydration not available on blocked-network platforms -->
2966
- <script>
2967
- console.warn('[FrontMCP] React hydration disabled - platform does not support external scripts');
2968
- </script>`;
2969
- }
2970
- }
2971
- return "";
2972
- }
2973
- function buildDataInjectionScript(options) {
2974
- const { toolName, input, output, structuredContent, widgetAccessible, hostContext } = options;
2975
- const helpers = createTemplateHelpers();
2976
- const contextData = {
2977
- theme: hostContext?.theme || "light",
2978
- displayMode: hostContext?.displayMode || "inline",
2979
- ...hostContext
2980
- };
2981
- return `<script>
2982
- // Tool metadata
2983
- window.__mcpToolName = ${helpers.jsonEmbed(toolName)};
2984
- window.__mcpToolInput = ${helpers.jsonEmbed(input)};
2985
- window.__mcpToolOutput = ${helpers.jsonEmbed(output)};
2986
- window.__mcpStructuredContent = ${helpers.jsonEmbed(structuredContent)};
2987
- window.__mcpWidgetAccessible = ${helpers.jsonEmbed(widgetAccessible)};
2988
- window.__mcpHostContext = ${helpers.jsonEmbed(contextData)};
2989
- </script>`;
2990
- }
2991
-
2992
- // libs/uipack/src/tool-template/builder.ts
2993
- init_utils();
2994
-
2995
- // libs/uipack/src/renderers/utils/detect.ts
2996
- var MAX_TEMPLATE_LENGTH = 5e4;
2997
- function isReactComponent(value) {
2998
- if (typeof value !== "function") {
2999
- return false;
3000
- }
3001
- const fn = value;
3002
- const typeofSymbol = fn.$$typeof;
3003
- if (typeofSymbol) {
3004
- const symbolString = typeofSymbol.toString();
3005
- return symbolString.includes("react.memo") || symbolString.includes("react.forward_ref") || symbolString.includes("react.lazy");
3006
- }
3007
- if (fn.prototype?.isReactComponent) {
3008
- return true;
3009
- }
3010
- if (fn.name && /^[A-Z]/.test(fn.name)) {
3011
- return true;
3012
- }
3013
- return false;
3014
- }
3015
- function isTemplateBuilderFunction(fn) {
3016
- if (isReactComponent(fn)) {
3017
- return false;
3018
- }
3019
- if (fn.name && /^[A-Z]/.test(fn.name)) {
3020
- return false;
3021
- }
3022
- return true;
3023
- }
3024
- function containsJsx(source) {
3025
- if (source.length > MAX_TEMPLATE_LENGTH) {
3026
- return false;
3027
- }
3028
- if (/<[A-Z][a-zA-Z0-9]*(\s|>|\/)/.test(source)) {
3029
- return true;
3030
- }
3031
- if (/<[A-Z][a-zA-Z0-9]*[^>]*\/>/.test(source)) {
3032
- return true;
3033
- }
3034
- if (/<[a-z]+[^>]*\{[^}]+\}/.test(source)) {
3035
- return true;
3036
- }
3037
- if (/\s(className|onClick|onChange|onSubmit|htmlFor)=/.test(source)) {
3038
- return true;
3039
- }
3040
- if (/<>|<\/>|<React\.Fragment>/.test(source)) {
3041
- return true;
3042
- }
3043
- if (/=>\s*\(?\s*</.test(source)) {
3044
- return true;
3045
- }
3046
- if (/return\s*\(?\s*</.test(source)) {
3047
- return true;
3048
- }
3049
- return false;
3050
- }
3051
- function containsMdxSyntax(source) {
3052
- if (source.length > MAX_TEMPLATE_LENGTH) {
3053
- return false;
3054
- }
3055
- if (/<[A-Z][a-zA-Z0-9]*/.test(source)) {
3056
- return true;
3057
- }
3058
- if (/^(import|export)\s/m.test(source)) {
3059
- return true;
3060
- }
3061
- if (/\s(className|onClick|onChange|onSubmit|htmlFor|dangerouslySetInnerHTML)=/.test(source)) {
3062
- return true;
3063
- }
3064
- if (/\{[^}"'\n]*\}/.test(source) && !/=\s*["'][^"']*\{/.test(source)) {
3065
- return true;
3066
- }
3067
- if (/^---[\s\S]*?---/m.test(source)) {
3068
- return true;
3069
- }
3070
- if (/<>|<\/>/.test(source)) {
3071
- return true;
3072
- }
3073
- return false;
3074
- }
3075
- function detectTemplateType(template) {
3076
- if (typeof template === "function") {
3077
- if (isReactComponent(template)) {
3078
- return {
3079
- type: "react",
3080
- confidence: 0.9,
3081
- reason: "Function detected as React component (PascalCase name or React symbols)"
3082
- };
3083
- }
3084
- return {
3085
- type: "html-function",
3086
- confidence: 0.8,
3087
- reason: "Function assumed to be HTML template builder"
3088
- };
3089
- }
3090
- if (typeof template === "string") {
3091
- if (containsMdxSyntax(template)) {
3092
- const hasMarkdown = /^#{1,6}\s|^\*\s|^\d+\.\s|^-\s/m.test(template);
3093
- if (hasMarkdown) {
3094
- return {
3095
- type: "mdx",
3096
- confidence: 0.9,
3097
- reason: "String contains Markdown with JSX components"
3098
- };
3099
- }
3100
- return {
3101
- type: "jsx-string",
3102
- confidence: 0.8,
3103
- reason: "String contains JSX syntax"
3104
- };
3105
- }
3106
- if (containsJsx(template)) {
3107
- return {
3108
- type: "jsx-string",
3109
- confidence: 0.85,
3110
- reason: "String contains JSX component tags or expressions"
3111
- };
3112
- }
3113
- return {
3114
- type: "html-string",
3115
- confidence: 1,
3116
- reason: "Plain HTML string"
3117
- };
3118
- }
3119
- return {
3120
- type: "html-string",
3121
- confidence: 0.5,
3122
- reason: "Unknown template type, defaulting to HTML"
3123
- };
3124
- }
3125
-
3126
- // libs/uipack/src/renderers/utils/hash.ts
3127
- function hashString(source) {
3128
- let hash = 2166136261;
3129
- for (let i = 0; i < source.length; i++) {
3130
- hash ^= source.charCodeAt(i);
3131
- hash = hash * 16777619 >>> 0;
3132
- }
3133
- return hash.toString(36);
3134
- }
3135
-
3136
- // libs/uipack/src/renderers/html.renderer.ts
3137
- var handlebarsRenderer = null;
3138
- async function loadHandlebarsRenderer() {
3139
- if (handlebarsRenderer !== null) {
3140
- return handlebarsRenderer;
3141
- }
3142
- try {
3143
- const handlebarsModule = await Promise.resolve().then(() => (init_handlebars(), handlebars_exports));
3144
- const { HandlebarsRenderer: HandlebarsRenderer2 } = handlebarsModule;
3145
- const renderer = new HandlebarsRenderer2();
3146
- handlebarsRenderer = {
3147
- render: (template, context) => renderer.render(template, {
3148
- input: context.input ?? {},
3149
- output: context.output,
3150
- structuredContent: context.structuredContent
3151
- }),
3152
- containsHandlebars: (template) => HandlebarsRenderer2.containsHandlebars(template)
3153
- };
3154
- return handlebarsRenderer;
3155
- } catch {
3156
- return null;
3157
- }
3158
- }
3159
- function containsHandlebars2(template) {
3160
- return /\{\{(?!!)[\s\S]*?\}\}/.test(template);
3161
- }
3162
- var HtmlRenderer = class {
3163
- type = "html";
3164
- priority = 0;
3165
- // Lowest priority - fallback renderer
3166
- /**
3167
- * Check if this renderer can handle the given template.
3168
- *
3169
- * Accepts:
3170
- * - Any string (assumed to be HTML, with or without Handlebars)
3171
- * - Functions that are template builders (not React components)
3172
- */
3173
- canHandle(template) {
3174
- if (typeof template === "string") {
3175
- return true;
3176
- }
3177
- if (typeof template === "function") {
3178
- return isTemplateBuilderFunction(template);
3179
- }
3180
- return false;
3181
- }
3182
- /**
3183
- * Check if a template uses Handlebars syntax.
3184
- *
3185
- * @param template - Template string to check
3186
- * @returns true if template contains {{...}} syntax
3187
- */
3188
- usesHandlebars(template) {
3189
- return containsHandlebars2(template);
3190
- }
3191
- /**
3192
- * Transpile the template.
3193
- *
3194
- * For HTML templates, no transpilation is needed.
3195
- * This method returns a dummy result for consistency.
3196
- */
3197
- async transpile(template, _options) {
3198
- const source = typeof template === "string" ? template : template.toString();
3199
- const hash = hashString(source);
3200
- return {
3201
- code: "",
3202
- // No transpiled code needed
3203
- hash,
3204
- cached: true
3205
- // Always "cached" since no work is done
3206
- };
3207
- }
3208
- /**
3209
- * Render the template to HTML string.
3210
- *
3211
- * For static strings without Handlebars, returns the string directly.
3212
- * For strings with Handlebars syntax, processes with HandlebarsRenderer.
3213
- * For functions, calls the function with the context.
3214
- */
3215
- async render(template, context, _options) {
3216
- if (typeof template === "string") {
3217
- if (containsHandlebars2(template)) {
3218
- return this.renderHandlebars(template, context);
3219
- }
3220
- return template;
3221
- }
3222
- if (typeof template === "function") {
3223
- const result = template(context);
3224
- if (typeof result === "string" && containsHandlebars2(result)) {
3225
- return this.renderHandlebars(result, context);
3226
- }
3227
- return result;
3228
- }
3229
- return String(template);
3230
- }
3231
- /**
3232
- * Render Handlebars template with context.
3233
- */
3234
- async renderHandlebars(template, context) {
3235
- const renderer = await loadHandlebarsRenderer();
3236
- if (!renderer) {
3237
- console.warn(
3238
- "[@frontmcp/ui] Template contains Handlebars syntax but handlebars is not installed. Install it for template interpolation: npm install handlebars"
3239
- );
3240
- return template;
3241
- }
3242
- return renderer.render(template, {
3243
- input: context.input,
3244
- output: context.output,
3245
- structuredContent: context.structuredContent
3246
- });
3247
- }
3248
- /**
3249
- * Get runtime scripts for client-side functionality.
3250
- *
3251
- * HTML templates don't need additional runtime scripts.
3252
- */
3253
- getRuntimeScripts(_platform) {
3254
- return {
3255
- headScripts: "",
3256
- isInline: false
3257
- };
3258
- }
3259
- };
3260
- var htmlRenderer = new HtmlRenderer();
3261
-
3262
- // libs/uipack/src/renderers/registry.ts
3263
- var RendererRegistry = class {
3264
- renderers = /* @__PURE__ */ new Map();
3265
- sortedRenderers = [];
3266
- defaultRenderer = "html";
3267
- debug;
3268
- constructor(options = {}) {
3269
- this.debug = options.debug ?? false;
3270
- this.register(htmlRenderer);
3271
- }
3272
- /**
3273
- * Register a renderer.
3274
- *
3275
- * Renderers are sorted by priority (highest first) for detection.
3276
- *
3277
- * @param renderer - Renderer to register
3278
- */
3279
- register(renderer) {
3280
- this.renderers.set(renderer.type, renderer);
3281
- this.updateSortedList();
3282
- if (this.debug) {
3283
- console.log(`[RendererRegistry] Registered renderer: ${renderer.type} (priority: ${renderer.priority})`);
3284
- }
3285
- }
3286
- /**
3287
- * Unregister a renderer.
3288
- *
3289
- * @param type - Type of renderer to remove
3290
- * @returns True if renderer was removed
3291
- */
3292
- unregister(type) {
3293
- const removed = this.renderers.delete(type);
3294
- if (removed) {
3295
- this.updateSortedList();
3296
- }
3297
- return removed;
3298
- }
3299
- /**
3300
- * Get a renderer by type.
3301
- *
3302
- * @param type - Renderer type
3303
- * @returns Renderer or undefined if not found
3304
- */
3305
- get(type) {
3306
- return this.renderers.get(type);
3307
- }
3308
- /**
3309
- * Check if a renderer type is registered.
3310
- *
3311
- * @param type - Renderer type
3312
- * @returns True if registered
3313
- */
3314
- has(type) {
3315
- return this.renderers.has(type);
3316
- }
3317
- /**
3318
- * Get all registered renderer types.
3319
- *
3320
- * @returns Array of renderer types
3321
- */
3322
- getTypes() {
3323
- return Array.from(this.renderers.keys());
3324
- }
3325
- /**
3326
- * Auto-detect the renderer for a template.
3327
- *
3328
- * Checks renderers in priority order (highest first).
3329
- * Returns HTML renderer as fallback.
3330
- *
3331
- * @param template - Template to detect
3332
- * @returns Detection result with renderer and confidence
3333
- */
3334
- detect(template) {
3335
- for (const renderer of this.sortedRenderers) {
3336
- if (renderer.canHandle(template)) {
3337
- const result = {
3338
- renderer,
3339
- confidence: renderer.priority / 100,
3340
- // Normalize to 0-1
3341
- reason: `Matched by ${renderer.type} renderer`
3342
- };
3343
- if (this.debug) {
3344
- console.log(`[RendererRegistry] Detected template as ${renderer.type} (confidence: ${result.confidence})`);
3345
- }
3346
- return result;
3347
- }
3348
- }
3349
- const fallback = this.renderers.get(this.defaultRenderer);
3350
- if (!fallback) {
3351
- throw new Error(`Default renderer '${this.defaultRenderer}' not found`);
3352
- }
3353
- return {
3354
- renderer: fallback,
3355
- confidence: 0.5,
3356
- reason: "Fallback to default HTML renderer"
3357
- };
3358
- }
3359
- /**
3360
- * Render a template with auto-detection.
3361
- *
3362
- * @param template - Template to render (React, MDX, or HTML)
3363
- * @param context - Template context with input/output
3364
- * @param options - Render options
3365
- * @returns Rendered result with HTML and metadata
3366
- */
3367
- async render(template, context, options = {}) {
3368
- const platform = options.platform ?? OPENAI_PLATFORM;
3369
- const detection = this.detect(template);
3370
- const renderer = detection.renderer;
3371
- if (this.debug) {
3372
- console.log(`[RendererRegistry] Rendering with ${renderer.type} renderer`);
3373
- }
3374
- const transpileResult = await renderer.transpile(template);
3375
- const html = await renderer.render(template, context, options);
3376
- const runtimeScripts = renderer.getRuntimeScripts(platform);
3377
- return {
3378
- html,
3379
- rendererType: renderer.type,
3380
- transpileCached: transpileResult.cached,
3381
- runtimeScripts
3382
- };
3383
- }
3384
- /**
3385
- * Render with a specific renderer type.
3386
- *
3387
- * @param type - Renderer type to use
3388
- * @param template - Template to render
3389
- * @param context - Template context
3390
- * @param options - Render options
3391
- * @returns Rendered result
3392
- */
3393
- async renderWith(type, template, context, options = {}) {
3394
- const renderer = this.renderers.get(type);
3395
- if (!renderer) {
3396
- throw new Error(`Renderer '${type}' not registered`);
3397
- }
3398
- const platform = options.platform ?? OPENAI_PLATFORM;
3399
- const transpileResult = await renderer.transpile(template);
3400
- const html = await renderer.render(template, context, options);
3401
- const runtimeScripts = renderer.getRuntimeScripts(platform);
3402
- return {
3403
- html,
3404
- rendererType: type,
3405
- transpileCached: transpileResult.cached,
3406
- runtimeScripts
3407
- };
3408
- }
3409
- /**
3410
- * Update the sorted renderer list by priority.
3411
- */
3412
- updateSortedList() {
3413
- this.sortedRenderers = Array.from(this.renderers.values()).sort((a, b) => b.priority - a.priority);
3414
- }
3415
- /**
3416
- * Set the default renderer type.
3417
- *
3418
- * @param type - Renderer type to use as default
3419
- */
3420
- setDefault(type) {
3421
- if (!this.renderers.has(type)) {
3422
- throw new Error(`Cannot set default to unregistered renderer '${type}'`);
3423
- }
3424
- this.defaultRenderer = type;
3425
- }
3426
- /**
3427
- * Get registry statistics.
3428
- */
3429
- getStats() {
3430
- return {
3431
- registeredRenderers: this.getTypes(),
3432
- defaultRenderer: this.defaultRenderer,
3433
- priorityOrder: this.sortedRenderers.map((r) => ({
3434
- type: r.type,
3435
- priority: r.priority
3436
- }))
3437
- };
3438
- }
3439
- };
3440
- var rendererRegistry = new RendererRegistry();
3441
-
3442
- // libs/uipack/src/tool-template/builder.ts
3443
- function buildTemplateContext(input, output, structuredContent) {
3444
- return {
3445
- input,
3446
- output,
3447
- structuredContent,
3448
- helpers: createTemplateHelpers()
3449
- };
3450
- }
3451
- function executeTemplate(template, ctx) {
3452
- if (typeof template === "string") {
3453
- return template;
3454
- }
3455
- return template(ctx);
3456
- }
3457
- async function renderTemplate2(template, ctx, options) {
3458
- const detection = detectTemplateType(template);
3459
- if (detection.type === "html-function" || detection.type === "html-string") {
3460
- const html = typeof template === "function" ? template(ctx) : template;
3461
- return { html, rendererType: "html" };
3462
- }
3463
- try {
3464
- const result = await rendererRegistry.render(template, ctx, {
3465
- hydrate: options?.hydrate,
3466
- mdxComponents: options?.mdxComponents
3467
- });
3468
- return { html: result.html, rendererType: result.rendererType };
3469
- } catch (error) {
3470
- console.warn(
3471
- `[@frontmcp/ui] Renderer failed for ${detection.type}, falling back to HTML:`,
3472
- error instanceof Error ? error.message : error
3473
- );
3474
- if (typeof template === "function") {
3475
- try {
3476
- const html = template(ctx);
3477
- return { html, rendererType: "html-fallback" };
3478
- } catch {
3479
- return {
3480
- html: `<div class="error">Template rendering failed: ${error instanceof Error ? error.message : "Unknown error"}</div>`,
3481
- rendererType: "error"
3482
- };
3483
- }
3484
- }
3485
- return { html: String(template), rendererType: "html-fallback" };
3486
- }
3487
- }
3488
- function renderToolTemplate(options) {
3489
- const { ui, toolName, input, output, structuredContent, theme, platform } = options;
3490
- const ctx = buildTemplateContext(input, output, structuredContent);
3491
- const content = executeTemplate(ui.template, ctx);
3492
- const wrapperOptions = {
3493
- content,
3494
- toolName,
3495
- input,
3496
- output,
3497
- structuredContent,
3498
- csp: ui.csp,
3499
- widgetAccessible: ui.widgetAccessible,
3500
- title: `${toolName} Result`,
3501
- theme,
3502
- platform
3503
- };
3504
- const html = wrapToolUI(wrapperOptions);
3505
- const openaiMeta = buildOpenAIMetaFromUI(ui);
3506
- return {
3507
- html,
3508
- mimeType: "text/html",
3509
- openaiMeta: Object.keys(openaiMeta).length > 0 ? openaiMeta : void 0
3510
- };
3511
- }
3512
- async function renderToolTemplateAsync(options) {
3513
- const { ui, toolName, input, output, structuredContent, theme, platform } = options;
3514
- const ctx = buildTemplateContext(input, output, structuredContent);
3515
- const { html: content, rendererType } = await renderTemplate2(ui.template, ctx, {
3516
- hydrate: ui.hydrate,
3517
- mdxComponents: ui.mdxComponents
3518
- });
3519
- const wrappedContent = ui.wrapper ? ui.wrapper(content, ctx) : content;
3520
- const wrapperOptions = {
3521
- content: wrappedContent,
3522
- toolName,
3523
- input,
3524
- output,
3525
- structuredContent,
3526
- csp: ui.csp,
3527
- widgetAccessible: ui.widgetAccessible,
3528
- title: `${toolName} Result`,
3529
- theme,
3530
- platform,
3531
- // Pass renderer type for framework runtime injection
3532
- rendererType,
3533
- hydrate: ui.hydrate
3534
- };
3535
- const html = wrapToolUI(wrapperOptions);
3536
- const openaiMeta = buildOpenAIMetaFromUI(ui);
3537
- return {
3538
- html,
3539
- mimeType: "text/html",
3540
- rendererType,
3541
- openaiMeta: Object.keys(openaiMeta).length > 0 ? openaiMeta : void 0
3542
- };
3543
- }
3544
- function buildOpenAIMetaFromUI(ui) {
3545
- const meta = {};
3546
- if (ui.widgetAccessible) {
3547
- meta["openai/widgetAccessible"] = true;
3548
- }
3549
- if (ui.widgetDescription) {
3550
- meta["openai/widgetDescription"] = ui.widgetDescription;
3551
- }
3552
- if (ui.csp) {
3553
- const cspConfig = {};
3554
- if (ui.csp.connectDomains?.length) {
3555
- cspConfig["connect_domains"] = ui.csp.connectDomains;
3556
- }
3557
- if (ui.csp.resourceDomains?.length) {
3558
- cspConfig["resource_domains"] = ui.csp.resourceDomains;
3559
- }
3560
- if (Object.keys(cspConfig).length > 0) {
3561
- meta["openai/widgetCSP"] = cspConfig;
3562
- }
3563
- }
3564
- if (ui.displayMode && ui.displayMode !== "inline") {
3565
- meta["openai/displayMode"] = ui.displayMode;
3566
- }
3567
- return meta;
3568
- }
3569
- function createTemplate(builder) {
3570
- return builder;
3571
- }
3572
- function createToolUI(config) {
3573
- return config;
3574
- }
3575
- function container(content, className = "") {
3576
- const baseClasses = "p-4 rounded-lg bg-surface";
3577
- return `<div class="${baseClasses} ${className}">${content}</div>`;
3578
- }
3579
- function heading(text, level = 2) {
3580
- const tag = `h${level}`;
3581
- const classes = {
3582
- 1: "text-2xl font-bold text-text-primary mb-4",
3583
- 2: "text-xl font-semibold text-text-primary mb-3",
3584
- 3: "text-lg font-medium text-text-primary mb-2",
3585
- 4: "text-base font-medium text-text-secondary mb-2"
3586
- }[level] || "";
3587
- return `<${tag} class="${classes}">${escapeHtml(text)}</${tag}>`;
3588
- }
3589
- function paragraph(text, className = "") {
3590
- return `<p class="text-text-secondary ${className}">${escapeHtml(text)}</p>`;
3591
- }
3592
- function keyValue(key, value, className = "") {
3593
- const displayValue = typeof value === "boolean" ? value ? "Yes" : "No" : String(value);
3594
- return `<div class="flex justify-between items-center py-2 border-b border-border ${className}">
3595
- <span class="text-text-secondary">${escapeHtml(key)}</span>
3596
- <span class="text-text-primary font-medium">${escapeHtml(displayValue)}</span>
3597
- </div>`;
3598
- }
3599
- function dataList(items) {
3600
- const listItems = items.map((item) => keyValue(item.key, item.value)).join("");
3601
- return `<div class="space-y-1">${listItems}</div>`;
3602
- }
3603
- function errorDisplay(message, details) {
3604
- return `<div class="p-4 bg-danger/10 border border-danger rounded-lg">
3605
- <div class="flex items-center gap-2 text-danger">
3606
- <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
3607
- <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/>
3608
- </svg>
3609
- <span class="font-medium">${escapeHtml(message)}</span>
3610
- </div>
3611
- ${details ? `<p class="mt-2 text-sm text-text-secondary">${escapeHtml(details)}</p>` : ""}
3612
- </div>`;
3613
- }
3614
- function successDisplay(message, details) {
3615
- return `<div class="p-4 bg-success/10 border border-success rounded-lg">
3616
- <div class="flex items-center gap-2 text-success">
3617
- <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
3618
- <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
3619
- </svg>
3620
- <span class="font-medium">${escapeHtml(message)}</span>
3621
- </div>
3622
- ${details ? `<p class="mt-2 text-sm text-text-secondary">${escapeHtml(details)}</p>` : ""}
3623
- </div>`;
3624
- }
3625
- function loadingDisplay(message = "Loading...") {
3626
- return `<div class="flex items-center justify-center p-8">
3627
- <div class="flex items-center gap-3 text-text-secondary">
3628
- <svg class="animate-spin w-5 h-5" fill="none" viewBox="0 0 24 24">
3629
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
3630
- <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
3631
- </svg>
3632
- <span>${escapeHtml(message)}</span>
3633
- </div>
3634
- </div>`;
3635
- }
3636
- export {
3637
- buildTemplateContext,
3638
- container,
3639
- createTemplate,
3640
- createToolUI,
3641
- dataList,
3642
- errorDisplay,
3643
- executeTemplate,
3644
- heading,
3645
- keyValue,
3646
- loadingDisplay,
3647
- paragraph,
3648
- renderTemplate2 as renderTemplate,
3649
- renderToolTemplate,
3650
- renderToolTemplateAsync,
3651
- successDisplay
3652
- };