@frontmcp/ui 0.6.0 → 0.6.2

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