@frontmcp/ui 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (805) hide show
  1. package/README.md +140 -362
  2. package/bridge/adapters/base-adapter.d.ts +104 -0
  3. package/bridge/adapters/base-adapter.d.ts.map +1 -0
  4. package/bridge/adapters/claude.adapter.d.ts +67 -0
  5. package/bridge/adapters/claude.adapter.d.ts.map +1 -0
  6. package/bridge/adapters/ext-apps.adapter.d.ts +143 -0
  7. package/bridge/adapters/ext-apps.adapter.d.ts.map +1 -0
  8. package/bridge/adapters/gemini.adapter.d.ts +64 -0
  9. package/bridge/adapters/gemini.adapter.d.ts.map +1 -0
  10. package/bridge/adapters/generic.adapter.d.ts +56 -0
  11. package/bridge/adapters/generic.adapter.d.ts.map +1 -0
  12. package/bridge/adapters/index.d.ts +26 -0
  13. package/bridge/adapters/index.d.ts.map +1 -0
  14. package/bridge/adapters/openai.adapter.d.ts +65 -0
  15. package/bridge/adapters/openai.adapter.d.ts.map +1 -0
  16. package/bridge/core/adapter-registry.d.ts +122 -0
  17. package/bridge/core/adapter-registry.d.ts.map +1 -0
  18. package/bridge/core/bridge-factory.d.ts +199 -0
  19. package/bridge/core/bridge-factory.d.ts.map +1 -0
  20. package/bridge/core/index.d.ts +10 -0
  21. package/bridge/core/index.d.ts.map +1 -0
  22. package/bridge/index.d.ts +62 -0
  23. package/bridge/index.d.ts.map +1 -0
  24. package/bridge/index.js +2540 -0
  25. package/bridge/runtime/iife-generator.d.ts +62 -0
  26. package/bridge/runtime/iife-generator.d.ts.map +1 -0
  27. package/bridge/runtime/index.d.ts +10 -0
  28. package/bridge/runtime/index.d.ts.map +1 -0
  29. package/bridge/types.d.ts +386 -0
  30. package/bridge/types.d.ts.map +1 -0
  31. package/bundler/bundler.d.ts +208 -0
  32. package/bundler/bundler.d.ts.map +1 -0
  33. package/bundler/cache.d.ts +173 -0
  34. package/bundler/cache.d.ts.map +1 -0
  35. package/bundler/file-cache/component-builder.d.ts +167 -0
  36. package/bundler/file-cache/component-builder.d.ts.map +1 -0
  37. package/bundler/file-cache/hash-calculator.d.ts +155 -0
  38. package/bundler/file-cache/hash-calculator.d.ts.map +1 -0
  39. package/bundler/file-cache/index.d.ts +12 -0
  40. package/bundler/file-cache/index.d.ts.map +1 -0
  41. package/bundler/file-cache/storage/filesystem.d.ts +149 -0
  42. package/bundler/file-cache/storage/filesystem.d.ts.map +1 -0
  43. package/bundler/file-cache/storage/index.d.ts +11 -0
  44. package/bundler/file-cache/storage/index.d.ts.map +1 -0
  45. package/bundler/file-cache/storage/interface.d.ts +152 -0
  46. package/bundler/file-cache/storage/interface.d.ts.map +1 -0
  47. package/bundler/file-cache/storage/redis.d.ts +139 -0
  48. package/bundler/file-cache/storage/redis.d.ts.map +1 -0
  49. package/bundler/index.d.ts +43 -0
  50. package/bundler/index.d.ts.map +1 -0
  51. package/bundler/index.js +3707 -0
  52. package/bundler/sandbox/enclave-adapter.d.ts +121 -0
  53. package/bundler/sandbox/enclave-adapter.d.ts.map +1 -0
  54. package/bundler/sandbox/executor.d.ts +14 -0
  55. package/bundler/sandbox/executor.d.ts.map +1 -0
  56. package/bundler/sandbox/policy.d.ts +62 -0
  57. package/bundler/sandbox/policy.d.ts.map +1 -0
  58. package/bundler/types.d.ts +702 -0
  59. package/bundler/types.d.ts.map +1 -0
  60. package/components/alert.d.ts +66 -0
  61. package/components/alert.d.ts.map +1 -0
  62. package/components/alert.schema.d.ts +98 -0
  63. package/components/alert.schema.d.ts.map +1 -0
  64. package/components/avatar.d.ts +77 -0
  65. package/components/avatar.d.ts.map +1 -0
  66. package/components/avatar.schema.d.ts +170 -0
  67. package/components/avatar.schema.d.ts.map +1 -0
  68. package/components/badge.d.ts +64 -0
  69. package/components/badge.d.ts.map +1 -0
  70. package/components/badge.schema.d.ts +91 -0
  71. package/components/badge.schema.d.ts.map +1 -0
  72. package/components/button.d.ts +100 -0
  73. package/components/button.d.ts.map +1 -0
  74. package/components/button.schema.d.ts +120 -0
  75. package/components/button.schema.d.ts.map +1 -0
  76. package/components/card.d.ts +53 -0
  77. package/components/card.d.ts.map +1 -0
  78. package/components/card.schema.d.ts +93 -0
  79. package/components/card.schema.d.ts.map +1 -0
  80. package/components/form.d.ts +212 -0
  81. package/components/form.d.ts.map +1 -0
  82. package/components/form.schema.d.ts +365 -0
  83. package/components/form.schema.d.ts.map +1 -0
  84. package/components/index.d.ts +29 -0
  85. package/components/index.d.ts.map +1 -0
  86. package/components/index.js +2525 -0
  87. package/components/list.d.ts +121 -0
  88. package/components/list.d.ts.map +1 -0
  89. package/components/list.schema.d.ts +129 -0
  90. package/components/list.schema.d.ts.map +1 -0
  91. package/components/modal.d.ts +100 -0
  92. package/components/modal.d.ts.map +1 -0
  93. package/components/modal.schema.d.ts +151 -0
  94. package/components/modal.schema.d.ts.map +1 -0
  95. package/components/table.d.ts +91 -0
  96. package/components/table.d.ts.map +1 -0
  97. package/components/table.schema.d.ts +123 -0
  98. package/components/table.schema.d.ts.map +1 -0
  99. package/esm/bridge/adapters/base-adapter.d.ts +104 -0
  100. package/esm/bridge/adapters/base-adapter.d.ts.map +1 -0
  101. package/esm/bridge/adapters/claude.adapter.d.ts +67 -0
  102. package/esm/bridge/adapters/claude.adapter.d.ts.map +1 -0
  103. package/esm/bridge/adapters/ext-apps.adapter.d.ts +143 -0
  104. package/esm/bridge/adapters/ext-apps.adapter.d.ts.map +1 -0
  105. package/esm/bridge/adapters/gemini.adapter.d.ts +64 -0
  106. package/esm/bridge/adapters/gemini.adapter.d.ts.map +1 -0
  107. package/esm/bridge/adapters/generic.adapter.d.ts +56 -0
  108. package/esm/bridge/adapters/generic.adapter.d.ts.map +1 -0
  109. package/esm/bridge/adapters/index.d.ts +26 -0
  110. package/esm/bridge/adapters/index.d.ts.map +1 -0
  111. package/esm/bridge/adapters/openai.adapter.d.ts +65 -0
  112. package/esm/bridge/adapters/openai.adapter.d.ts.map +1 -0
  113. package/esm/bridge/core/adapter-registry.d.ts +122 -0
  114. package/esm/bridge/core/adapter-registry.d.ts.map +1 -0
  115. package/esm/bridge/core/bridge-factory.d.ts +199 -0
  116. package/esm/bridge/core/bridge-factory.d.ts.map +1 -0
  117. package/esm/bridge/core/index.d.ts +10 -0
  118. package/esm/bridge/core/index.d.ts.map +1 -0
  119. package/esm/bridge/index.d.ts +62 -0
  120. package/esm/bridge/index.d.ts.map +1 -0
  121. package/esm/bridge/index.js +2487 -0
  122. package/esm/bridge/runtime/iife-generator.d.ts +62 -0
  123. package/esm/bridge/runtime/iife-generator.d.ts.map +1 -0
  124. package/esm/bridge/runtime/index.d.ts +10 -0
  125. package/esm/bridge/runtime/index.d.ts.map +1 -0
  126. package/esm/bridge/types.d.ts +386 -0
  127. package/esm/bridge/types.d.ts.map +1 -0
  128. package/esm/bundler/bundler.d.ts +208 -0
  129. package/esm/bundler/bundler.d.ts.map +1 -0
  130. package/esm/bundler/cache.d.ts +173 -0
  131. package/esm/bundler/cache.d.ts.map +1 -0
  132. package/esm/bundler/file-cache/component-builder.d.ts +167 -0
  133. package/esm/bundler/file-cache/component-builder.d.ts.map +1 -0
  134. package/esm/bundler/file-cache/hash-calculator.d.ts +155 -0
  135. package/esm/bundler/file-cache/hash-calculator.d.ts.map +1 -0
  136. package/esm/bundler/file-cache/index.d.ts +12 -0
  137. package/esm/bundler/file-cache/index.d.ts.map +1 -0
  138. package/esm/bundler/file-cache/storage/filesystem.d.ts +149 -0
  139. package/esm/bundler/file-cache/storage/filesystem.d.ts.map +1 -0
  140. package/esm/bundler/file-cache/storage/index.d.ts +11 -0
  141. package/esm/bundler/file-cache/storage/index.d.ts.map +1 -0
  142. package/esm/bundler/file-cache/storage/interface.d.ts +152 -0
  143. package/esm/bundler/file-cache/storage/interface.d.ts.map +1 -0
  144. package/esm/bundler/file-cache/storage/redis.d.ts +139 -0
  145. package/esm/bundler/file-cache/storage/redis.d.ts.map +1 -0
  146. package/esm/bundler/index.d.ts +43 -0
  147. package/esm/bundler/index.d.ts.map +1 -0
  148. package/esm/bundler/index.js +3640 -0
  149. package/esm/bundler/sandbox/enclave-adapter.d.ts +121 -0
  150. package/esm/bundler/sandbox/enclave-adapter.d.ts.map +1 -0
  151. package/esm/bundler/sandbox/executor.d.ts +14 -0
  152. package/esm/bundler/sandbox/executor.d.ts.map +1 -0
  153. package/esm/bundler/sandbox/policy.d.ts +62 -0
  154. package/esm/bundler/sandbox/policy.d.ts.map +1 -0
  155. package/esm/bundler/types.d.ts +702 -0
  156. package/esm/bundler/types.d.ts.map +1 -0
  157. package/esm/components/alert.d.ts +66 -0
  158. package/esm/components/alert.d.ts.map +1 -0
  159. package/esm/components/alert.schema.d.ts +98 -0
  160. package/esm/components/alert.schema.d.ts.map +1 -0
  161. package/esm/components/avatar.d.ts +77 -0
  162. package/esm/components/avatar.d.ts.map +1 -0
  163. package/esm/components/avatar.schema.d.ts +170 -0
  164. package/esm/components/avatar.schema.d.ts.map +1 -0
  165. package/esm/components/badge.d.ts +64 -0
  166. package/esm/components/badge.d.ts.map +1 -0
  167. package/esm/components/badge.schema.d.ts +91 -0
  168. package/esm/components/badge.schema.d.ts.map +1 -0
  169. package/esm/components/button.d.ts +100 -0
  170. package/esm/components/button.d.ts.map +1 -0
  171. package/esm/components/button.schema.d.ts +120 -0
  172. package/esm/components/button.schema.d.ts.map +1 -0
  173. package/esm/components/card.d.ts +53 -0
  174. package/esm/components/card.d.ts.map +1 -0
  175. package/esm/components/card.schema.d.ts +93 -0
  176. package/esm/components/card.schema.d.ts.map +1 -0
  177. package/esm/components/form.d.ts +212 -0
  178. package/esm/components/form.d.ts.map +1 -0
  179. package/esm/components/form.schema.d.ts +365 -0
  180. package/esm/components/form.schema.d.ts.map +1 -0
  181. package/esm/components/index.d.ts +29 -0
  182. package/esm/components/index.d.ts.map +1 -0
  183. package/esm/components/index.js +2396 -0
  184. package/esm/components/list.d.ts +121 -0
  185. package/esm/components/list.d.ts.map +1 -0
  186. package/esm/components/list.schema.d.ts +129 -0
  187. package/esm/components/list.schema.d.ts.map +1 -0
  188. package/esm/components/modal.d.ts +100 -0
  189. package/esm/components/modal.d.ts.map +1 -0
  190. package/esm/components/modal.schema.d.ts +151 -0
  191. package/esm/components/modal.schema.d.ts.map +1 -0
  192. package/esm/components/table.d.ts +91 -0
  193. package/esm/components/table.d.ts.map +1 -0
  194. package/esm/components/table.schema.d.ts +123 -0
  195. package/esm/components/table.schema.d.ts.map +1 -0
  196. package/esm/index.d.ts +40 -0
  197. package/esm/index.d.ts.map +1 -0
  198. package/esm/index.js +8326 -0
  199. package/esm/layouts/base.d.ts +86 -0
  200. package/esm/layouts/base.d.ts.map +1 -0
  201. package/esm/layouts/index.d.ts +8 -0
  202. package/esm/layouts/index.d.ts.map +1 -0
  203. package/esm/layouts/index.js +409 -0
  204. package/esm/layouts/presets.d.ts +134 -0
  205. package/esm/layouts/presets.d.ts.map +1 -0
  206. package/esm/package.json +72 -0
  207. package/esm/pages/consent.d.ts +117 -0
  208. package/esm/pages/consent.d.ts.map +1 -0
  209. package/esm/pages/error.d.ts +101 -0
  210. package/esm/pages/error.d.ts.map +1 -0
  211. package/esm/pages/index.d.ts +9 -0
  212. package/esm/pages/index.d.ts.map +1 -0
  213. package/esm/pages/index.js +1036 -0
  214. package/esm/react/Alert.d.ts +101 -0
  215. package/esm/react/Alert.d.ts.map +1 -0
  216. package/esm/react/Badge.d.ts +100 -0
  217. package/esm/react/Badge.d.ts.map +1 -0
  218. package/esm/react/Button.d.ts +108 -0
  219. package/esm/react/Button.d.ts.map +1 -0
  220. package/esm/react/Card.d.ts +103 -0
  221. package/esm/react/Card.d.ts.map +1 -0
  222. package/esm/react/hooks/context.d.ts +179 -0
  223. package/esm/react/hooks/context.d.ts.map +1 -0
  224. package/esm/react/hooks/index.d.ts +42 -0
  225. package/esm/react/hooks/index.d.ts.map +1 -0
  226. package/esm/react/hooks/tools.d.ts +284 -0
  227. package/esm/react/hooks/tools.d.ts.map +1 -0
  228. package/esm/react/index.d.ts +80 -0
  229. package/esm/react/index.d.ts.map +1 -0
  230. package/esm/react/index.js +3124 -0
  231. package/esm/react/types.d.ts +105 -0
  232. package/esm/react/types.d.ts.map +1 -0
  233. package/esm/react/utils.d.ts +43 -0
  234. package/esm/react/utils.d.ts.map +1 -0
  235. package/esm/render/index.d.ts +8 -0
  236. package/esm/render/index.d.ts.map +1 -0
  237. package/esm/render/index.js +45 -0
  238. package/esm/render/prerender.d.ts +57 -0
  239. package/esm/render/prerender.d.ts.map +1 -0
  240. package/esm/renderers/index.d.ts +21 -0
  241. package/esm/renderers/index.d.ts.map +1 -0
  242. package/esm/renderers/index.js +381 -0
  243. package/esm/renderers/react.adapter.d.ts +70 -0
  244. package/esm/renderers/react.adapter.d.ts.map +1 -0
  245. package/esm/renderers/react.renderer.d.ts +96 -0
  246. package/esm/renderers/react.renderer.d.ts.map +1 -0
  247. package/esm/universal/UniversalApp.d.ts +108 -0
  248. package/esm/universal/UniversalApp.d.ts.map +1 -0
  249. package/esm/universal/cached-runtime.d.ts +115 -0
  250. package/esm/universal/cached-runtime.d.ts.map +1 -0
  251. package/esm/universal/context.d.ts +122 -0
  252. package/esm/universal/context.d.ts.map +1 -0
  253. package/esm/universal/index.d.ts +57 -0
  254. package/esm/universal/index.d.ts.map +1 -0
  255. package/esm/universal/index.js +1755 -0
  256. package/esm/universal/renderers/html.renderer.d.ts +37 -0
  257. package/esm/universal/renderers/html.renderer.d.ts.map +1 -0
  258. package/esm/universal/renderers/index.d.ts +112 -0
  259. package/esm/universal/renderers/index.d.ts.map +1 -0
  260. package/esm/universal/renderers/markdown.renderer.d.ts +33 -0
  261. package/esm/universal/renderers/markdown.renderer.d.ts.map +1 -0
  262. package/esm/universal/renderers/mdx.renderer.d.ts +38 -0
  263. package/esm/universal/renderers/mdx.renderer.d.ts.map +1 -0
  264. package/esm/universal/renderers/react.renderer.d.ts +46 -0
  265. package/esm/universal/renderers/react.renderer.d.ts.map +1 -0
  266. package/esm/universal/runtime-builder.d.ts +33 -0
  267. package/esm/universal/runtime-builder.d.ts.map +1 -0
  268. package/esm/universal/store.d.ts +135 -0
  269. package/esm/universal/store.d.ts.map +1 -0
  270. package/esm/universal/types.d.ts +199 -0
  271. package/esm/universal/types.d.ts.map +1 -0
  272. package/esm/web-components/core/attribute-parser.d.ts +82 -0
  273. package/esm/web-components/core/attribute-parser.d.ts.map +1 -0
  274. package/esm/web-components/core/base-element.d.ts +197 -0
  275. package/esm/web-components/core/base-element.d.ts.map +1 -0
  276. package/esm/web-components/core/index.d.ts +9 -0
  277. package/esm/web-components/core/index.d.ts.map +1 -0
  278. package/esm/web-components/elements/fmcp-alert.d.ts +46 -0
  279. package/esm/web-components/elements/fmcp-alert.d.ts.map +1 -0
  280. package/esm/web-components/elements/fmcp-badge.d.ts +47 -0
  281. package/esm/web-components/elements/fmcp-badge.d.ts.map +1 -0
  282. package/esm/web-components/elements/fmcp-button.d.ts +117 -0
  283. package/esm/web-components/elements/fmcp-button.d.ts.map +1 -0
  284. package/esm/web-components/elements/fmcp-card.d.ts +53 -0
  285. package/esm/web-components/elements/fmcp-card.d.ts.map +1 -0
  286. package/esm/web-components/elements/fmcp-input.d.ts +96 -0
  287. package/esm/web-components/elements/fmcp-input.d.ts.map +1 -0
  288. package/esm/web-components/elements/fmcp-select.d.ts +100 -0
  289. package/esm/web-components/elements/fmcp-select.d.ts.map +1 -0
  290. package/esm/web-components/elements/index.d.ts +13 -0
  291. package/esm/web-components/elements/index.d.ts.map +1 -0
  292. package/esm/web-components/index.d.ts +50 -0
  293. package/esm/web-components/index.d.ts.map +1 -0
  294. package/esm/web-components/index.js +1993 -0
  295. package/esm/web-components/register.d.ts +57 -0
  296. package/esm/web-components/register.d.ts.map +1 -0
  297. package/esm/web-components/types.d.ts +122 -0
  298. package/esm/web-components/types.d.ts.map +1 -0
  299. package/esm/widgets/index.d.ts +8 -0
  300. package/esm/widgets/index.d.ts.map +1 -0
  301. package/esm/widgets/index.js +883 -0
  302. package/esm/widgets/progress.d.ts +133 -0
  303. package/esm/widgets/progress.d.ts.map +1 -0
  304. package/esm/widgets/resource.d.ts +163 -0
  305. package/esm/widgets/resource.d.ts.map +1 -0
  306. package/index.d.ts +40 -0
  307. package/index.d.ts.map +1 -0
  308. package/index.js +8526 -0
  309. package/layouts/base.d.ts +86 -0
  310. package/layouts/base.d.ts.map +1 -0
  311. package/layouts/index.d.ts +8 -0
  312. package/layouts/index.d.ts.map +1 -0
  313. package/layouts/index.js +437 -0
  314. package/layouts/presets.d.ts +134 -0
  315. package/layouts/presets.d.ts.map +1 -0
  316. package/package.json +33 -110
  317. package/pages/consent.d.ts +117 -0
  318. package/pages/consent.d.ts.map +1 -0
  319. package/pages/error.d.ts +101 -0
  320. package/pages/error.d.ts.map +1 -0
  321. package/pages/index.d.ts +9 -0
  322. package/pages/index.d.ts.map +1 -0
  323. package/pages/index.js +1065 -0
  324. package/react/Alert.d.ts +101 -0
  325. package/react/Alert.d.ts.map +1 -0
  326. package/react/Badge.d.ts +100 -0
  327. package/react/Badge.d.ts.map +1 -0
  328. package/react/Button.d.ts +108 -0
  329. package/react/Button.d.ts.map +1 -0
  330. package/react/Card.d.ts +103 -0
  331. package/react/Card.d.ts.map +1 -0
  332. package/react/hooks/context.d.ts +179 -0
  333. package/react/hooks/context.d.ts.map +1 -0
  334. package/react/hooks/index.d.ts +42 -0
  335. package/react/hooks/index.d.ts.map +1 -0
  336. package/react/hooks/tools.d.ts +284 -0
  337. package/react/hooks/tools.d.ts.map +1 -0
  338. package/react/index.d.ts +80 -0
  339. package/react/index.d.ts.map +1 -0
  340. package/react/index.js +3160 -0
  341. package/react/types.d.ts +105 -0
  342. package/react/types.d.ts.map +1 -0
  343. package/react/utils.d.ts +43 -0
  344. package/react/utils.d.ts.map +1 -0
  345. package/render/index.d.ts +8 -0
  346. package/render/index.d.ts.map +1 -0
  347. package/render/index.js +77 -0
  348. package/render/prerender.d.ts +57 -0
  349. package/render/prerender.d.ts.map +1 -0
  350. package/renderers/index.d.ts +21 -0
  351. package/renderers/index.d.ts.map +1 -0
  352. package/renderers/index.js +416 -0
  353. package/renderers/react.adapter.d.ts +70 -0
  354. package/renderers/react.adapter.d.ts.map +1 -0
  355. package/renderers/react.renderer.d.ts +96 -0
  356. package/renderers/react.renderer.d.ts.map +1 -0
  357. package/universal/UniversalApp.d.ts +108 -0
  358. package/universal/UniversalApp.d.ts.map +1 -0
  359. package/universal/cached-runtime.d.ts +115 -0
  360. package/universal/cached-runtime.d.ts.map +1 -0
  361. package/universal/context.d.ts +122 -0
  362. package/universal/context.d.ts.map +1 -0
  363. package/universal/index.d.ts +57 -0
  364. package/universal/index.d.ts.map +1 -0
  365. package/universal/index.js +1841 -0
  366. package/universal/renderers/html.renderer.d.ts +37 -0
  367. package/universal/renderers/html.renderer.d.ts.map +1 -0
  368. package/universal/renderers/index.d.ts +112 -0
  369. package/universal/renderers/index.d.ts.map +1 -0
  370. package/universal/renderers/markdown.renderer.d.ts +33 -0
  371. package/universal/renderers/markdown.renderer.d.ts.map +1 -0
  372. package/universal/renderers/mdx.renderer.d.ts +38 -0
  373. package/universal/renderers/mdx.renderer.d.ts.map +1 -0
  374. package/universal/renderers/react.renderer.d.ts +46 -0
  375. package/universal/renderers/react.renderer.d.ts.map +1 -0
  376. package/universal/runtime-builder.d.ts +33 -0
  377. package/universal/runtime-builder.d.ts.map +1 -0
  378. package/universal/store.d.ts +135 -0
  379. package/universal/store.d.ts.map +1 -0
  380. package/universal/types.d.ts +199 -0
  381. package/universal/types.d.ts.map +1 -0
  382. package/web-components/core/attribute-parser.d.ts +82 -0
  383. package/web-components/core/attribute-parser.d.ts.map +1 -0
  384. package/web-components/core/base-element.d.ts +197 -0
  385. package/web-components/core/base-element.d.ts.map +1 -0
  386. package/web-components/core/index.d.ts +9 -0
  387. package/web-components/core/index.d.ts.map +1 -0
  388. package/web-components/elements/fmcp-alert.d.ts +46 -0
  389. package/web-components/elements/fmcp-alert.d.ts.map +1 -0
  390. package/web-components/elements/fmcp-badge.d.ts +47 -0
  391. package/web-components/elements/fmcp-badge.d.ts.map +1 -0
  392. package/web-components/elements/fmcp-button.d.ts +117 -0
  393. package/web-components/elements/fmcp-button.d.ts.map +1 -0
  394. package/web-components/elements/fmcp-card.d.ts +53 -0
  395. package/web-components/elements/fmcp-card.d.ts.map +1 -0
  396. package/web-components/elements/fmcp-input.d.ts +96 -0
  397. package/web-components/elements/fmcp-input.d.ts.map +1 -0
  398. package/web-components/elements/fmcp-select.d.ts +100 -0
  399. package/web-components/elements/fmcp-select.d.ts.map +1 -0
  400. package/web-components/elements/index.d.ts +13 -0
  401. package/web-components/elements/index.d.ts.map +1 -0
  402. package/web-components/index.d.ts +50 -0
  403. package/web-components/index.d.ts.map +1 -0
  404. package/web-components/index.js +2028 -0
  405. package/web-components/register.d.ts +57 -0
  406. package/web-components/register.d.ts.map +1 -0
  407. package/web-components/types.d.ts +122 -0
  408. package/web-components/types.d.ts.map +1 -0
  409. package/widgets/index.d.ts +8 -0
  410. package/widgets/index.d.ts.map +1 -0
  411. package/widgets/index.js +910 -0
  412. package/widgets/progress.d.ts +133 -0
  413. package/widgets/progress.d.ts.map +1 -0
  414. package/widgets/resource.d.ts +163 -0
  415. package/widgets/resource.d.ts.map +1 -0
  416. package/src/adapters/index.d.ts +0 -10
  417. package/src/adapters/index.js +0 -18
  418. package/src/adapters/index.js.map +0 -1
  419. package/src/adapters/platform-meta.d.ts +0 -165
  420. package/src/adapters/platform-meta.js +0 -310
  421. package/src/adapters/platform-meta.js.map +0 -1
  422. package/src/base-template/bridge.d.ts +0 -89
  423. package/src/base-template/bridge.js +0 -452
  424. package/src/base-template/bridge.js.map +0 -1
  425. package/src/base-template/default-base-template.d.ts +0 -91
  426. package/src/base-template/default-base-template.js +0 -435
  427. package/src/base-template/default-base-template.js.map +0 -1
  428. package/src/base-template/index.d.ts +0 -14
  429. package/src/base-template/index.js +0 -30
  430. package/src/base-template/index.js.map +0 -1
  431. package/src/base-template/polyfills.d.ts +0 -30
  432. package/src/base-template/polyfills.js +0 -190
  433. package/src/base-template/polyfills.js.map +0 -1
  434. package/src/base-template/theme-styles.d.ts +0 -73
  435. package/src/base-template/theme-styles.js +0 -95
  436. package/src/base-template/theme-styles.js.map +0 -1
  437. package/src/bridge/adapters/base-adapter.d.ts +0 -103
  438. package/src/bridge/adapters/base-adapter.js +0 -314
  439. package/src/bridge/adapters/base-adapter.js.map +0 -1
  440. package/src/bridge/adapters/claude.adapter.d.ts +0 -66
  441. package/src/bridge/adapters/claude.adapter.js +0 -145
  442. package/src/bridge/adapters/claude.adapter.js.map +0 -1
  443. package/src/bridge/adapters/ext-apps.adapter.d.ts +0 -142
  444. package/src/bridge/adapters/ext-apps.adapter.js +0 -416
  445. package/src/bridge/adapters/ext-apps.adapter.js.map +0 -1
  446. package/src/bridge/adapters/gemini.adapter.d.ts +0 -63
  447. package/src/bridge/adapters/gemini.adapter.js +0 -160
  448. package/src/bridge/adapters/gemini.adapter.js.map +0 -1
  449. package/src/bridge/adapters/generic.adapter.d.ts +0 -55
  450. package/src/bridge/adapters/generic.adapter.js +0 -108
  451. package/src/bridge/adapters/generic.adapter.js.map +0 -1
  452. package/src/bridge/adapters/index.d.ts +0 -25
  453. package/src/bridge/adapters/index.js +0 -65
  454. package/src/bridge/adapters/index.js.map +0 -1
  455. package/src/bridge/adapters/openai.adapter.d.ts +0 -64
  456. package/src/bridge/adapters/openai.adapter.js +0 -194
  457. package/src/bridge/adapters/openai.adapter.js.map +0 -1
  458. package/src/bridge/core/adapter-registry.d.ts +0 -121
  459. package/src/bridge/core/adapter-registry.js +0 -271
  460. package/src/bridge/core/adapter-registry.js.map +0 -1
  461. package/src/bridge/core/bridge-factory.d.ts +0 -198
  462. package/src/bridge/core/bridge-factory.js +0 -428
  463. package/src/bridge/core/bridge-factory.js.map +0 -1
  464. package/src/bridge/core/index.d.ts +0 -9
  465. package/src/bridge/core/index.js +0 -22
  466. package/src/bridge/core/index.js.map +0 -1
  467. package/src/bridge/index.d.ts +0 -61
  468. package/src/bridge/index.js +0 -94
  469. package/src/bridge/index.js.map +0 -1
  470. package/src/bridge/runtime/iife-generator.d.ts +0 -61
  471. package/src/bridge/runtime/iife-generator.js +0 -940
  472. package/src/bridge/runtime/iife-generator.js.map +0 -1
  473. package/src/bridge/runtime/index.d.ts +0 -8
  474. package/src/bridge/runtime/index.js +0 -16
  475. package/src/bridge/runtime/index.js.map +0 -1
  476. package/src/bridge/types.d.ts +0 -385
  477. package/src/bridge/types.js +0 -11
  478. package/src/bridge/types.js.map +0 -1
  479. package/src/build/cdn-resources.d.ts +0 -140
  480. package/src/build/cdn-resources.js +0 -314
  481. package/src/build/cdn-resources.js.map +0 -1
  482. package/src/build/index.d.ts +0 -294
  483. package/src/build/index.js +0 -325
  484. package/src/build/index.js.map +0 -1
  485. package/src/build/widget-manifest.d.ts +0 -212
  486. package/src/build/widget-manifest.js +0 -652
  487. package/src/build/widget-manifest.js.map +0 -1
  488. package/src/bundler/bundler.d.ts +0 -110
  489. package/src/bundler/bundler.js +0 -432
  490. package/src/bundler/bundler.js.map +0 -1
  491. package/src/bundler/cache.d.ts +0 -172
  492. package/src/bundler/cache.js +0 -250
  493. package/src/bundler/cache.js.map +0 -1
  494. package/src/bundler/index.d.ts +0 -41
  495. package/src/bundler/index.js +0 -73
  496. package/src/bundler/index.js.map +0 -1
  497. package/src/bundler/sandbox/enclave-adapter.d.ts +0 -120
  498. package/src/bundler/sandbox/enclave-adapter.js +0 -339
  499. package/src/bundler/sandbox/enclave-adapter.js.map +0 -1
  500. package/src/bundler/sandbox/executor.d.ts +0 -13
  501. package/src/bundler/sandbox/executor.js +0 -22
  502. package/src/bundler/sandbox/executor.js.map +0 -1
  503. package/src/bundler/sandbox/policy.d.ts +0 -61
  504. package/src/bundler/sandbox/policy.js +0 -238
  505. package/src/bundler/sandbox/policy.js.map +0 -1
  506. package/src/bundler/types.d.ts +0 -347
  507. package/src/bundler/types.js +0 -132
  508. package/src/bundler/types.js.map +0 -1
  509. package/src/components/alert.d.ts +0 -71
  510. package/src/components/alert.js +0 -189
  511. package/src/components/alert.js.map +0 -1
  512. package/src/components/alert.schema.d.ts +0 -114
  513. package/src/components/alert.schema.js +0 -105
  514. package/src/components/alert.schema.js.map +0 -1
  515. package/src/components/avatar.d.ts +0 -76
  516. package/src/components/avatar.js +0 -176
  517. package/src/components/avatar.js.map +0 -1
  518. package/src/components/avatar.schema.d.ts +0 -169
  519. package/src/components/avatar.schema.js +0 -103
  520. package/src/components/avatar.schema.js.map +0 -1
  521. package/src/components/badge.d.ts +0 -70
  522. package/src/components/badge.js +0 -149
  523. package/src/components/badge.js.map +0 -1
  524. package/src/components/badge.schema.d.ts +0 -109
  525. package/src/components/badge.schema.js +0 -96
  526. package/src/components/badge.schema.js.map +0 -1
  527. package/src/components/button.d.ts +0 -111
  528. package/src/components/button.js +0 -336
  529. package/src/components/button.js.map +0 -1
  530. package/src/components/button.schema.d.ts +0 -148
  531. package/src/components/button.schema.js +0 -121
  532. package/src/components/button.schema.js.map +0 -1
  533. package/src/components/card.d.ts +0 -60
  534. package/src/components/card.js +0 -117
  535. package/src/components/card.js.map +0 -1
  536. package/src/components/card.schema.d.ts +0 -113
  537. package/src/components/card.schema.js +0 -98
  538. package/src/components/card.schema.js.map +0 -1
  539. package/src/components/form.d.ts +0 -239
  540. package/src/components/form.js +0 -420
  541. package/src/components/form.js.map +0 -1
  542. package/src/components/form.schema.d.ts +0 -441
  543. package/src/components/form.schema.js +0 -406
  544. package/src/components/form.schema.js.map +0 -1
  545. package/src/components/index.d.ts +0 -29
  546. package/src/components/index.js +0 -98
  547. package/src/components/index.js.map +0 -1
  548. package/src/components/list.d.ts +0 -127
  549. package/src/components/list.js +0 -279
  550. package/src/components/list.js.map +0 -1
  551. package/src/components/list.schema.d.ts +0 -134
  552. package/src/components/list.schema.js +0 -168
  553. package/src/components/list.schema.js.map +0 -1
  554. package/src/components/modal.d.ts +0 -111
  555. package/src/components/modal.js +0 -260
  556. package/src/components/modal.js.map +0 -1
  557. package/src/components/modal.schema.d.ts +0 -186
  558. package/src/components/modal.schema.js +0 -167
  559. package/src/components/modal.schema.js.map +0 -1
  560. package/src/components/table.d.ts +0 -105
  561. package/src/components/table.js +0 -283
  562. package/src/components/table.js.map +0 -1
  563. package/src/components/table.schema.d.ts +0 -159
  564. package/src/components/table.schema.js +0 -173
  565. package/src/components/table.schema.js.map +0 -1
  566. package/src/handlebars/helpers.d.ts +0 -348
  567. package/src/handlebars/helpers.js +0 -605
  568. package/src/handlebars/helpers.js.map +0 -1
  569. package/src/handlebars/index.d.ts +0 -193
  570. package/src/handlebars/index.js +0 -350
  571. package/src/handlebars/index.js.map +0 -1
  572. package/src/index.d.ts +0 -50
  573. package/src/index.js +0 -192
  574. package/src/index.js.map +0 -1
  575. package/src/layouts/base.d.ts +0 -88
  576. package/src/layouts/base.js +0 -227
  577. package/src/layouts/base.js.map +0 -1
  578. package/src/layouts/index.d.ts +0 -7
  579. package/src/layouts/index.js +0 -25
  580. package/src/layouts/index.js.map +0 -1
  581. package/src/layouts/presets.d.ts +0 -133
  582. package/src/layouts/presets.js +0 -277
  583. package/src/layouts/presets.js.map +0 -1
  584. package/src/pages/consent.d.ts +0 -116
  585. package/src/pages/consent.js +0 -218
  586. package/src/pages/consent.js.map +0 -1
  587. package/src/pages/error.d.ts +0 -100
  588. package/src/pages/error.js +0 -263
  589. package/src/pages/error.js.map +0 -1
  590. package/src/pages/index.d.ts +0 -8
  591. package/src/pages/index.js +0 -27
  592. package/src/pages/index.js.map +0 -1
  593. package/src/react/Alert.d.ts +0 -101
  594. package/src/react/Alert.js +0 -51
  595. package/src/react/Alert.js.map +0 -1
  596. package/src/react/Badge.d.ts +0 -100
  597. package/src/react/Badge.js +0 -55
  598. package/src/react/Badge.js.map +0 -1
  599. package/src/react/Button.d.ts +0 -108
  600. package/src/react/Button.js +0 -52
  601. package/src/react/Button.js.map +0 -1
  602. package/src/react/Card.d.ts +0 -103
  603. package/src/react/Card.js +0 -55
  604. package/src/react/Card.js.map +0 -1
  605. package/src/react/hooks/context.d.ts +0 -178
  606. package/src/react/hooks/context.js +0 -287
  607. package/src/react/hooks/context.js.map +0 -1
  608. package/src/react/hooks/index.d.ts +0 -41
  609. package/src/react/hooks/index.js +0 -61
  610. package/src/react/hooks/index.js.map +0 -1
  611. package/src/react/hooks/tools.d.ts +0 -283
  612. package/src/react/hooks/tools.js +0 -465
  613. package/src/react/hooks/tools.js.map +0 -1
  614. package/src/react/index.d.ts +0 -80
  615. package/src/react/index.js +0 -113
  616. package/src/react/index.js.map +0 -1
  617. package/src/react/types.d.ts +0 -105
  618. package/src/react/types.js +0 -12
  619. package/src/react/types.js.map +0 -1
  620. package/src/react/utils.d.ts +0 -42
  621. package/src/react/utils.js +0 -99
  622. package/src/react/utils.js.map +0 -1
  623. package/src/registry/index.d.ts +0 -45
  624. package/src/registry/index.js +0 -67
  625. package/src/registry/index.js.map +0 -1
  626. package/src/registry/render-template.d.ts +0 -86
  627. package/src/registry/render-template.js +0 -239
  628. package/src/registry/render-template.js.map +0 -1
  629. package/src/registry/tool-ui.registry.d.ts +0 -260
  630. package/src/registry/tool-ui.registry.js +0 -438
  631. package/src/registry/tool-ui.registry.js.map +0 -1
  632. package/src/registry/uri-utils.d.ts +0 -55
  633. package/src/registry/uri-utils.js +0 -97
  634. package/src/registry/uri-utils.js.map +0 -1
  635. package/src/render/index.d.ts +0 -7
  636. package/src/render/index.js +0 -14
  637. package/src/render/index.js.map +0 -1
  638. package/src/render/prerender.d.ts +0 -56
  639. package/src/render/prerender.js +0 -98
  640. package/src/render/prerender.js.map +0 -1
  641. package/src/renderers/cache.d.ts +0 -144
  642. package/src/renderers/cache.js +0 -240
  643. package/src/renderers/cache.js.map +0 -1
  644. package/src/renderers/html.renderer.d.ts +0 -122
  645. package/src/renderers/html.renderer.js +0 -204
  646. package/src/renderers/html.renderer.js.map +0 -1
  647. package/src/renderers/index.d.ts +0 -35
  648. package/src/renderers/index.js +0 -70
  649. package/src/renderers/index.js.map +0 -1
  650. package/src/renderers/mdx.renderer.d.ts +0 -119
  651. package/src/renderers/mdx.renderer.js +0 -305
  652. package/src/renderers/mdx.renderer.js.map +0 -1
  653. package/src/renderers/react.renderer.d.ts +0 -95
  654. package/src/renderers/react.renderer.js +0 -260
  655. package/src/renderers/react.renderer.js.map +0 -1
  656. package/src/renderers/registry.d.ts +0 -133
  657. package/src/renderers/registry.js +0 -232
  658. package/src/renderers/registry.js.map +0 -1
  659. package/src/renderers/types.d.ts +0 -341
  660. package/src/renderers/types.js +0 -9
  661. package/src/renderers/types.js.map +0 -1
  662. package/src/renderers/utils/detect.d.ts +0 -106
  663. package/src/renderers/utils/detect.js +0 -267
  664. package/src/renderers/utils/detect.js.map +0 -1
  665. package/src/renderers/utils/hash.d.ts +0 -39
  666. package/src/renderers/utils/hash.js +0 -75
  667. package/src/renderers/utils/hash.js.map +0 -1
  668. package/src/renderers/utils/index.d.ts +0 -8
  669. package/src/renderers/utils/index.js +0 -28
  670. package/src/renderers/utils/index.js.map +0 -1
  671. package/src/renderers/utils/transpiler.d.ts +0 -88
  672. package/src/renderers/utils/transpiler.js +0 -215
  673. package/src/renderers/utils/transpiler.js.map +0 -1
  674. package/src/runtime/adapters/html.adapter.d.ts +0 -58
  675. package/src/runtime/adapters/html.adapter.js +0 -131
  676. package/src/runtime/adapters/html.adapter.js.map +0 -1
  677. package/src/runtime/adapters/index.d.ts +0 -25
  678. package/src/runtime/adapters/index.js +0 -54
  679. package/src/runtime/adapters/index.js.map +0 -1
  680. package/src/runtime/adapters/mdx.adapter.d.ts +0 -72
  681. package/src/runtime/adapters/mdx.adapter.js +0 -241
  682. package/src/runtime/adapters/mdx.adapter.js.map +0 -1
  683. package/src/runtime/adapters/react.adapter.d.ts +0 -69
  684. package/src/runtime/adapters/react.adapter.js +0 -245
  685. package/src/runtime/adapters/react.adapter.js.map +0 -1
  686. package/src/runtime/adapters/types.d.ts +0 -94
  687. package/src/runtime/adapters/types.js +0 -11
  688. package/src/runtime/adapters/types.js.map +0 -1
  689. package/src/runtime/csp.d.ts +0 -37
  690. package/src/runtime/csp.js +0 -140
  691. package/src/runtime/csp.js.map +0 -1
  692. package/src/runtime/index.d.ts +0 -16
  693. package/src/runtime/index.js +0 -72
  694. package/src/runtime/index.js.map +0 -1
  695. package/src/runtime/mcp-bridge.d.ts +0 -100
  696. package/src/runtime/mcp-bridge.js +0 -581
  697. package/src/runtime/mcp-bridge.js.map +0 -1
  698. package/src/runtime/renderer-runtime.d.ts +0 -132
  699. package/src/runtime/renderer-runtime.js +0 -389
  700. package/src/runtime/renderer-runtime.js.map +0 -1
  701. package/src/runtime/sanitizer.d.ts +0 -171
  702. package/src/runtime/sanitizer.js +0 -318
  703. package/src/runtime/sanitizer.js.map +0 -1
  704. package/src/runtime/types.d.ts +0 -414
  705. package/src/runtime/types.js +0 -12
  706. package/src/runtime/types.js.map +0 -1
  707. package/src/runtime/wrapper.d.ts +0 -375
  708. package/src/runtime/wrapper.js +0 -1793
  709. package/src/runtime/wrapper.js.map +0 -1
  710. package/src/styles/index.d.ts +0 -7
  711. package/src/styles/index.js +0 -11
  712. package/src/styles/index.js.map +0 -1
  713. package/src/styles/variants.d.ts +0 -50
  714. package/src/styles/variants.js +0 -175
  715. package/src/styles/variants.js.map +0 -1
  716. package/src/theme/cdn.d.ts +0 -194
  717. package/src/theme/cdn.js +0 -375
  718. package/src/theme/cdn.js.map +0 -1
  719. package/src/theme/index.d.ts +0 -17
  720. package/src/theme/index.js +0 -57
  721. package/src/theme/index.js.map +0 -1
  722. package/src/theme/platforms.d.ts +0 -106
  723. package/src/theme/platforms.js +0 -161
  724. package/src/theme/platforms.js.map +0 -1
  725. package/src/theme/presets/github-openai.d.ts +0 -49
  726. package/src/theme/presets/github-openai.js +0 -189
  727. package/src/theme/presets/github-openai.js.map +0 -1
  728. package/src/theme/presets/index.d.ts +0 -10
  729. package/src/theme/presets/index.js +0 -17
  730. package/src/theme/presets/index.js.map +0 -1
  731. package/src/theme/theme.d.ts +0 -395
  732. package/src/theme/theme.js +0 -332
  733. package/src/theme/theme.js.map +0 -1
  734. package/src/tool-template/builder.d.ts +0 -212
  735. package/src/tool-template/builder.js +0 -397
  736. package/src/tool-template/builder.js.map +0 -1
  737. package/src/tool-template/index.d.ts +0 -15
  738. package/src/tool-template/index.js +0 -38
  739. package/src/tool-template/index.js.map +0 -1
  740. package/src/types/index.d.ts +0 -13
  741. package/src/types/index.js +0 -26
  742. package/src/types/index.js.map +0 -1
  743. package/src/types/ui-config.d.ts +0 -357
  744. package/src/types/ui-config.js +0 -12
  745. package/src/types/ui-config.js.map +0 -1
  746. package/src/types/ui-runtime.d.ts +0 -965
  747. package/src/types/ui-runtime.js +0 -117
  748. package/src/types/ui-runtime.js.map +0 -1
  749. package/src/validation/error-box.d.ts +0 -55
  750. package/src/validation/error-box.js +0 -75
  751. package/src/validation/error-box.js.map +0 -1
  752. package/src/validation/index.d.ts +0 -12
  753. package/src/validation/index.js +0 -21
  754. package/src/validation/index.js.map +0 -1
  755. package/src/validation/wrapper.d.ts +0 -96
  756. package/src/validation/wrapper.js +0 -117
  757. package/src/validation/wrapper.js.map +0 -1
  758. package/src/web-components/core/attribute-parser.d.ts +0 -85
  759. package/src/web-components/core/attribute-parser.js +0 -189
  760. package/src/web-components/core/attribute-parser.js.map +0 -1
  761. package/src/web-components/core/base-element.d.ts +0 -197
  762. package/src/web-components/core/base-element.js +0 -289
  763. package/src/web-components/core/base-element.js.map +0 -1
  764. package/src/web-components/core/index.d.ts +0 -8
  765. package/src/web-components/core/index.js +0 -18
  766. package/src/web-components/core/index.js.map +0 -1
  767. package/src/web-components/elements/fmcp-alert.d.ts +0 -45
  768. package/src/web-components/elements/fmcp-alert.js +0 -93
  769. package/src/web-components/elements/fmcp-alert.js.map +0 -1
  770. package/src/web-components/elements/fmcp-badge.d.ts +0 -46
  771. package/src/web-components/elements/fmcp-badge.js +0 -99
  772. package/src/web-components/elements/fmcp-badge.js.map +0 -1
  773. package/src/web-components/elements/fmcp-button.d.ts +0 -124
  774. package/src/web-components/elements/fmcp-button.js +0 -233
  775. package/src/web-components/elements/fmcp-button.js.map +0 -1
  776. package/src/web-components/elements/fmcp-card.d.ts +0 -52
  777. package/src/web-components/elements/fmcp-card.js +0 -115
  778. package/src/web-components/elements/fmcp-card.js.map +0 -1
  779. package/src/web-components/elements/fmcp-input.d.ts +0 -95
  780. package/src/web-components/elements/fmcp-input.js +0 -248
  781. package/src/web-components/elements/fmcp-input.js.map +0 -1
  782. package/src/web-components/elements/fmcp-select.d.ts +0 -99
  783. package/src/web-components/elements/fmcp-select.js +0 -243
  784. package/src/web-components/elements/fmcp-select.js.map +0 -1
  785. package/src/web-components/elements/index.d.ts +0 -12
  786. package/src/web-components/elements/index.js +0 -34
  787. package/src/web-components/elements/index.js.map +0 -1
  788. package/src/web-components/index.d.ts +0 -49
  789. package/src/web-components/index.js +0 -75
  790. package/src/web-components/index.js.map +0 -1
  791. package/src/web-components/register.d.ts +0 -56
  792. package/src/web-components/register.js +0 -80
  793. package/src/web-components/register.js.map +0 -1
  794. package/src/web-components/types.d.ts +0 -121
  795. package/src/web-components/types.js +0 -25
  796. package/src/web-components/types.js.map +0 -1
  797. package/src/widgets/index.d.ts +0 -7
  798. package/src/widgets/index.js +0 -24
  799. package/src/widgets/index.js.map +0 -1
  800. package/src/widgets/progress.d.ts +0 -132
  801. package/src/widgets/progress.js +0 -303
  802. package/src/widgets/progress.js.map +0 -1
  803. package/src/widgets/resource.d.ts +0 -162
  804. package/src/widgets/resource.js +0 -340
  805. package/src/widgets/resource.js.map +0 -1
@@ -0,0 +1,3640 @@
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/bundler/file-cache/storage/interface.ts
12
+ function calculateManifestSize(manifest) {
13
+ try {
14
+ return Buffer.byteLength(JSON.stringify(manifest), "utf8");
15
+ } catch {
16
+ return 0;
17
+ }
18
+ }
19
+ var DEFAULT_STORAGE_OPTIONS;
20
+ var init_interface = __esm({
21
+ "libs/ui/src/bundler/file-cache/storage/interface.ts"() {
22
+ "use strict";
23
+ DEFAULT_STORAGE_OPTIONS = {
24
+ maxEntries: 1e3,
25
+ maxSize: 100 * 1024 * 1024,
26
+ // 100MB
27
+ defaultTtl: 24 * 60 * 60,
28
+ // 24 hours
29
+ compress: false
30
+ };
31
+ }
32
+ });
33
+
34
+ // libs/ui/src/bundler/file-cache/storage/filesystem.ts
35
+ var filesystem_exports = {};
36
+ __export(filesystem_exports, {
37
+ CacheInitializationError: () => CacheInitializationError,
38
+ CacheOperationError: () => CacheOperationError,
39
+ FilesystemStorage: () => FilesystemStorage,
40
+ StorageNotInitializedError: () => StorageNotInitializedError,
41
+ createFilesystemStorage: () => createFilesystemStorage
42
+ });
43
+ import { mkdir, readFile, writeFile, readdir, unlink, rm } from "fs/promises";
44
+ import { join, dirname } from "path";
45
+ import { existsSync } from "fs";
46
+ import { createHash } from "crypto";
47
+ function createFilesystemStorage(options) {
48
+ return new FilesystemStorage(options);
49
+ }
50
+ var CacheInitializationError, CacheOperationError, StorageNotInitializedError, DEFAULT_FS_OPTIONS, FilesystemStorage;
51
+ var init_filesystem = __esm({
52
+ "libs/ui/src/bundler/file-cache/storage/filesystem.ts"() {
53
+ "use strict";
54
+ init_interface();
55
+ CacheInitializationError = class extends Error {
56
+ cause;
57
+ constructor(message, cause) {
58
+ super(message);
59
+ this.name = "CacheInitializationError";
60
+ this.cause = cause;
61
+ }
62
+ };
63
+ CacheOperationError = class extends Error {
64
+ cause;
65
+ constructor(message, cause) {
66
+ super(message);
67
+ this.name = "CacheOperationError";
68
+ this.cause = cause;
69
+ }
70
+ };
71
+ StorageNotInitializedError = class extends Error {
72
+ constructor() {
73
+ super("Storage not initialized. Call initialize() first.");
74
+ this.name = "StorageNotInitializedError";
75
+ }
76
+ };
77
+ DEFAULT_FS_OPTIONS = {
78
+ ...DEFAULT_STORAGE_OPTIONS,
79
+ cacheDir: ".frontmcp-cache/builds",
80
+ extension: ".json"
81
+ };
82
+ FilesystemStorage = class {
83
+ type = "filesystem";
84
+ options;
85
+ initialized = false;
86
+ stats = {
87
+ entries: 0,
88
+ totalSize: 0,
89
+ hits: 0,
90
+ misses: 0,
91
+ hitRate: 0
92
+ };
93
+ constructor(options = {}) {
94
+ this.options = {
95
+ ...DEFAULT_FS_OPTIONS,
96
+ ...options
97
+ };
98
+ }
99
+ /**
100
+ * Initialize the storage directory.
101
+ */
102
+ async initialize() {
103
+ if (this.initialized) return;
104
+ try {
105
+ await mkdir(this.options.cacheDir, { recursive: true });
106
+ await this.loadStats();
107
+ this.initialized = true;
108
+ } catch (error) {
109
+ throw new CacheInitializationError(`Failed to initialize cache directory: ${error}`, error);
110
+ }
111
+ }
112
+ /**
113
+ * Get a cached manifest.
114
+ */
115
+ async get(key) {
116
+ this.ensureInitialized();
117
+ const filePath = this.getFilePath(key);
118
+ try {
119
+ if (!existsSync(filePath)) {
120
+ this.stats.misses++;
121
+ this.updateHitRate();
122
+ return void 0;
123
+ }
124
+ const content = await readFile(filePath, "utf8");
125
+ const entry = JSON.parse(content);
126
+ if (Date.now() > entry.metadata.expiresAt) {
127
+ await this.delete(key);
128
+ this.stats.misses++;
129
+ this.updateHitRate();
130
+ return void 0;
131
+ }
132
+ entry.metadata.lastAccessedAt = Date.now();
133
+ entry.metadata.accessCount++;
134
+ this.writeEntry(filePath, entry).catch((err) => {
135
+ if (process.env["DEBUG"]) {
136
+ console.debug(`[FilesystemStorage] Failed to update cache metadata for ${key}: ${err}`);
137
+ }
138
+ });
139
+ this.stats.hits++;
140
+ this.updateHitRate();
141
+ return entry.data;
142
+ } catch {
143
+ this.stats.misses++;
144
+ this.updateHitRate();
145
+ return void 0;
146
+ }
147
+ }
148
+ /**
149
+ * Store a manifest in cache.
150
+ */
151
+ async set(key, manifest, ttl) {
152
+ this.ensureInitialized();
153
+ const filePath = this.getFilePath(key);
154
+ const size = calculateManifestSize(manifest);
155
+ const effectiveTtl = ttl ?? this.options.defaultTtl;
156
+ await this.ensureCapacity(size);
157
+ const entry = {
158
+ data: manifest,
159
+ metadata: {
160
+ key,
161
+ size,
162
+ createdAt: Date.now(),
163
+ expiresAt: Date.now() + effectiveTtl * 1e3,
164
+ lastAccessedAt: Date.now(),
165
+ accessCount: 0
166
+ }
167
+ };
168
+ await this.writeEntry(filePath, entry);
169
+ this.stats.entries++;
170
+ this.stats.totalSize += size;
171
+ }
172
+ /**
173
+ * Check if a key exists.
174
+ */
175
+ async has(key) {
176
+ this.ensureInitialized();
177
+ const filePath = this.getFilePath(key);
178
+ try {
179
+ if (!existsSync(filePath)) return false;
180
+ const content = await readFile(filePath, "utf8");
181
+ const entry = JSON.parse(content);
182
+ if (Date.now() > entry.metadata.expiresAt) {
183
+ await this.delete(key);
184
+ return false;
185
+ }
186
+ return true;
187
+ } catch {
188
+ return false;
189
+ }
190
+ }
191
+ /**
192
+ * Delete a cached entry.
193
+ */
194
+ async delete(key) {
195
+ this.ensureInitialized();
196
+ const filePath = this.getFilePath(key);
197
+ try {
198
+ if (!existsSync(filePath)) return false;
199
+ const content = await readFile(filePath, "utf8");
200
+ const entry = JSON.parse(content);
201
+ await unlink(filePath);
202
+ this.stats.entries = Math.max(0, this.stats.entries - 1);
203
+ this.stats.totalSize = Math.max(0, this.stats.totalSize - entry.metadata.size);
204
+ return true;
205
+ } catch {
206
+ return false;
207
+ }
208
+ }
209
+ /**
210
+ * Clear all cached entries.
211
+ */
212
+ async clear() {
213
+ this.ensureInitialized();
214
+ try {
215
+ await rm(this.options.cacheDir, { recursive: true, force: true });
216
+ await mkdir(this.options.cacheDir, { recursive: true });
217
+ this.stats = {
218
+ entries: 0,
219
+ totalSize: 0,
220
+ hits: 0,
221
+ misses: 0,
222
+ hitRate: 0
223
+ };
224
+ } catch (error) {
225
+ throw new CacheOperationError(`Failed to clear cache: ${error}`, error);
226
+ }
227
+ }
228
+ /**
229
+ * Get cache statistics.
230
+ */
231
+ async getStats() {
232
+ return { ...this.stats };
233
+ }
234
+ /**
235
+ * Clean up expired entries.
236
+ */
237
+ async cleanup() {
238
+ this.ensureInitialized();
239
+ let removed = 0;
240
+ try {
241
+ const files = await readdir(this.options.cacheDir);
242
+ for (const file of files) {
243
+ if (!file.endsWith(this.options.extension)) continue;
244
+ const filePath = join(this.options.cacheDir, file);
245
+ try {
246
+ const content = await readFile(filePath, "utf8");
247
+ const entry = JSON.parse(content);
248
+ if (Date.now() > entry.metadata.expiresAt) {
249
+ await unlink(filePath);
250
+ this.stats.entries = Math.max(0, this.stats.entries - 1);
251
+ this.stats.totalSize = Math.max(0, this.stats.totalSize - entry.metadata.size);
252
+ removed++;
253
+ }
254
+ } catch {
255
+ await unlink(filePath).catch(() => {
256
+ });
257
+ removed++;
258
+ }
259
+ }
260
+ } catch {
261
+ }
262
+ return removed;
263
+ }
264
+ /**
265
+ * Close the storage (no-op for filesystem).
266
+ */
267
+ async close() {
268
+ }
269
+ /**
270
+ * Get the file path for a cache key.
271
+ * Uses SHA-256 hash to avoid collisions from key sanitization.
272
+ */
273
+ getFilePath(key) {
274
+ const hash = createHash("sha256").update(key).digest("hex").slice(0, 16);
275
+ return join(this.options.cacheDir, `${hash}${this.options.extension}`);
276
+ }
277
+ /**
278
+ * Write a cache entry to disk.
279
+ */
280
+ async writeEntry(filePath, entry) {
281
+ await mkdir(dirname(filePath), { recursive: true });
282
+ await writeFile(filePath, JSON.stringify(entry, null, 2), "utf8");
283
+ }
284
+ /**
285
+ * Ensure the storage is initialized.
286
+ */
287
+ ensureInitialized() {
288
+ if (!this.initialized) {
289
+ throw new StorageNotInitializedError();
290
+ }
291
+ }
292
+ /**
293
+ * Load stats from existing cache files.
294
+ * Reads entry metadata to get accurate manifest sizes.
295
+ */
296
+ async loadStats() {
297
+ try {
298
+ const files = await readdir(this.options.cacheDir);
299
+ let entries = 0;
300
+ let totalSize = 0;
301
+ for (const file of files) {
302
+ if (!file.endsWith(this.options.extension)) continue;
303
+ const filePath = join(this.options.cacheDir, file);
304
+ try {
305
+ const content = await readFile(filePath, "utf8");
306
+ const entry = JSON.parse(content);
307
+ entries++;
308
+ totalSize += entry.metadata.size;
309
+ } catch {
310
+ }
311
+ }
312
+ this.stats.entries = entries;
313
+ this.stats.totalSize = totalSize;
314
+ } catch {
315
+ }
316
+ }
317
+ /**
318
+ * Ensure there's capacity for a new entry.
319
+ */
320
+ async ensureCapacity(newEntrySize) {
321
+ if (this.stats.entries >= this.options.maxEntries) {
322
+ await this.evictLRU();
323
+ }
324
+ while (this.stats.totalSize + newEntrySize > this.options.maxSize) {
325
+ const evicted = await this.evictLRU();
326
+ if (!evicted) break;
327
+ }
328
+ }
329
+ /**
330
+ * Evict the least recently used entry.
331
+ */
332
+ async evictLRU() {
333
+ try {
334
+ const files = await readdir(this.options.cacheDir);
335
+ let oldestKey = null;
336
+ let oldestTime = Infinity;
337
+ let corruptedFile = null;
338
+ for (const file of files) {
339
+ if (!file.endsWith(this.options.extension)) continue;
340
+ const filePath = join(this.options.cacheDir, file);
341
+ try {
342
+ const content = await readFile(filePath, "utf8");
343
+ const entry = JSON.parse(content);
344
+ if (entry.metadata.lastAccessedAt < oldestTime) {
345
+ oldestTime = entry.metadata.lastAccessedAt;
346
+ oldestKey = entry.metadata.key;
347
+ }
348
+ } catch {
349
+ corruptedFile = filePath;
350
+ }
351
+ }
352
+ if (corruptedFile) {
353
+ try {
354
+ await unlink(corruptedFile);
355
+ this.stats.entries = Math.max(0, this.stats.entries - 1);
356
+ return true;
357
+ } catch {
358
+ return false;
359
+ }
360
+ }
361
+ if (oldestKey) {
362
+ return await this.delete(oldestKey);
363
+ }
364
+ return false;
365
+ } catch {
366
+ return false;
367
+ }
368
+ }
369
+ /**
370
+ * Update hit rate statistic.
371
+ */
372
+ updateHitRate() {
373
+ const total = this.stats.hits + this.stats.misses;
374
+ this.stats.hitRate = total > 0 ? this.stats.hits / total : 0;
375
+ }
376
+ };
377
+ }
378
+ });
379
+
380
+ // libs/ui/src/bundler/file-cache/storage/redis.ts
381
+ var redis_exports = {};
382
+ __export(redis_exports, {
383
+ RedisStorage: () => RedisStorage,
384
+ createRedisStorage: () => createRedisStorage
385
+ });
386
+ function createRedisStorage(options) {
387
+ return new RedisStorage(options);
388
+ }
389
+ var STATS_KEY_SUFFIX, RedisStorage;
390
+ var init_redis = __esm({
391
+ "libs/ui/src/bundler/file-cache/storage/redis.ts"() {
392
+ "use strict";
393
+ init_interface();
394
+ STATS_KEY_SUFFIX = ":__stats__";
395
+ RedisStorage = class {
396
+ type = "redis";
397
+ options;
398
+ initialized = false;
399
+ localStats = {
400
+ entries: 0,
401
+ totalSize: 0,
402
+ hits: 0,
403
+ misses: 0,
404
+ hitRate: 0
405
+ };
406
+ constructor(options) {
407
+ if (!options.client) {
408
+ throw new Error("Redis client is required");
409
+ }
410
+ this.options = {
411
+ ...DEFAULT_STORAGE_OPTIONS,
412
+ keyPrefix: "frontmcp:ui:build:",
413
+ json: true,
414
+ ...options
415
+ };
416
+ }
417
+ /**
418
+ * Initialize the Redis connection.
419
+ */
420
+ async initialize() {
421
+ if (this.initialized) return;
422
+ try {
423
+ await this.options.client.ping();
424
+ await this.loadStats();
425
+ this.initialized = true;
426
+ } catch (error) {
427
+ throw new Error(`Failed to connect to Redis: ${error}`);
428
+ }
429
+ }
430
+ /**
431
+ * Get a cached manifest.
432
+ */
433
+ async get(key) {
434
+ this.ensureInitialized();
435
+ const redisKey = this.getRedisKey(key);
436
+ try {
437
+ const data = await this.options.client.get(redisKey);
438
+ if (!data) {
439
+ this.localStats.misses++;
440
+ this.updateHitRate();
441
+ await this.persistStats();
442
+ return void 0;
443
+ }
444
+ const entry = JSON.parse(data);
445
+ entry.metadata.lastAccessedAt = Date.now();
446
+ entry.metadata.accessCount++;
447
+ const ttl = await this.options.client.ttl(redisKey);
448
+ if (ttl > 0) {
449
+ const serialized = JSON.stringify(entry);
450
+ await this.options.client.setex(redisKey, ttl, serialized);
451
+ }
452
+ this.localStats.hits++;
453
+ this.updateHitRate();
454
+ await this.persistStats();
455
+ return entry.data;
456
+ } catch (error) {
457
+ console.warn?.(`Redis cache get failed for key "${key}": ${error}`);
458
+ this.localStats.misses++;
459
+ this.updateHitRate();
460
+ await this.persistStats().catch(() => {
461
+ });
462
+ return void 0;
463
+ }
464
+ }
465
+ /**
466
+ * Store a manifest in cache.
467
+ */
468
+ async set(key, manifest, ttl) {
469
+ this.ensureInitialized();
470
+ const redisKey = this.getRedisKey(key);
471
+ const size = calculateManifestSize(manifest);
472
+ const effectiveTtl = ttl ?? this.options.defaultTtl;
473
+ const entry = {
474
+ data: manifest,
475
+ metadata: {
476
+ key,
477
+ size,
478
+ createdAt: Date.now(),
479
+ expiresAt: Date.now() + effectiveTtl * 1e3,
480
+ lastAccessedAt: Date.now(),
481
+ accessCount: 0
482
+ }
483
+ };
484
+ const serialized = JSON.stringify(entry);
485
+ await this.options.client.setex(redisKey, effectiveTtl, serialized);
486
+ this.localStats.entries++;
487
+ this.localStats.totalSize += size;
488
+ await this.persistStats();
489
+ }
490
+ /**
491
+ * Check if a key exists.
492
+ */
493
+ async has(key) {
494
+ this.ensureInitialized();
495
+ const redisKey = this.getRedisKey(key);
496
+ const exists = await this.options.client.exists(redisKey);
497
+ return exists > 0;
498
+ }
499
+ /**
500
+ * Delete a cached entry.
501
+ */
502
+ async delete(key) {
503
+ this.ensureInitialized();
504
+ const redisKey = this.getRedisKey(key);
505
+ try {
506
+ const data = await this.options.client.get(redisKey);
507
+ if (data) {
508
+ const entry = JSON.parse(data);
509
+ this.localStats.totalSize = Math.max(0, this.localStats.totalSize - entry.metadata.size);
510
+ }
511
+ } catch {
512
+ }
513
+ const deleted = await this.options.client.del(redisKey);
514
+ if (deleted > 0) {
515
+ this.localStats.entries = Math.max(0, this.localStats.entries - 1);
516
+ await this.persistStats();
517
+ return true;
518
+ }
519
+ return false;
520
+ }
521
+ /**
522
+ * Clear all cached entries.
523
+ */
524
+ async clear() {
525
+ this.ensureInitialized();
526
+ const pattern = `${this.options.keyPrefix}*`;
527
+ const keys = await this.options.client.keys(pattern);
528
+ if (keys.length > 0) {
529
+ await this.options.client.del(keys);
530
+ }
531
+ this.localStats = {
532
+ entries: 0,
533
+ totalSize: 0,
534
+ hits: 0,
535
+ misses: 0,
536
+ hitRate: 0
537
+ };
538
+ await this.persistStats();
539
+ }
540
+ /**
541
+ * Get cache statistics.
542
+ */
543
+ async getStats() {
544
+ await this.loadStats();
545
+ return { ...this.localStats };
546
+ }
547
+ /**
548
+ * Clean up expired entries.
549
+ * Redis handles TTL expiration automatically, so this just refreshes stats.
550
+ */
551
+ async cleanup() {
552
+ this.ensureInitialized();
553
+ const pattern = `${this.options.keyPrefix}*`;
554
+ const keys = await this.options.client.keys(pattern);
555
+ const dataKeys = keys.filter((k) => !k.endsWith(STATS_KEY_SUFFIX));
556
+ const previousCount = this.localStats.entries;
557
+ this.localStats.entries = dataKeys.length;
558
+ let totalSize = 0;
559
+ for (const key of dataKeys) {
560
+ try {
561
+ const data = await this.options.client.get(key);
562
+ if (data) {
563
+ const entry = JSON.parse(data);
564
+ totalSize += entry.metadata.size;
565
+ }
566
+ } catch {
567
+ }
568
+ }
569
+ this.localStats.totalSize = totalSize;
570
+ await this.persistStats();
571
+ return Math.max(0, previousCount - this.localStats.entries);
572
+ }
573
+ /**
574
+ * Close the Redis connection.
575
+ */
576
+ async close() {
577
+ await this.options.client.quit();
578
+ }
579
+ /**
580
+ * Get the Redis key for a cache key.
581
+ */
582
+ getRedisKey(key) {
583
+ return `${this.options.keyPrefix}${key}`;
584
+ }
585
+ /**
586
+ * Get the Redis key for stats.
587
+ */
588
+ getStatsKey() {
589
+ return `${this.options.keyPrefix}${STATS_KEY_SUFFIX}`;
590
+ }
591
+ /**
592
+ * Ensure the storage is initialized.
593
+ */
594
+ ensureInitialized() {
595
+ if (!this.initialized) {
596
+ throw new Error("Storage not initialized. Call initialize() first.");
597
+ }
598
+ }
599
+ /**
600
+ * Load stats from Redis.
601
+ */
602
+ async loadStats() {
603
+ try {
604
+ const statsKey = this.getStatsKey();
605
+ const data = await this.options.client.get(statsKey);
606
+ if (data) {
607
+ const savedStats = JSON.parse(data);
608
+ this.localStats = {
609
+ ...this.localStats,
610
+ ...savedStats
611
+ };
612
+ }
613
+ } catch {
614
+ }
615
+ }
616
+ /**
617
+ * Persist stats to Redis.
618
+ */
619
+ async persistStats() {
620
+ try {
621
+ const statsKey = this.getStatsKey();
622
+ const serialized = JSON.stringify(this.localStats);
623
+ await this.options.client.set(statsKey, serialized);
624
+ } catch {
625
+ }
626
+ }
627
+ /**
628
+ * Update hit rate statistic.
629
+ */
630
+ updateHitRate() {
631
+ const total = this.localStats.hits + this.localStats.misses;
632
+ this.localStats.hitRate = total > 0 ? this.localStats.hits / total : 0;
633
+ }
634
+ };
635
+ }
636
+ });
637
+
638
+ // libs/ui/src/bundler/types.ts
639
+ var DEFAULT_SECURITY_POLICY = {
640
+ allowedImports: [/^react$/, /^react-dom$/, /^react\/jsx-runtime$/, /^react\/jsx-dev-runtime$/, /^@frontmcp\/ui/],
641
+ blockedImports: [
642
+ /^fs$/,
643
+ /^fs\//,
644
+ /^net$/,
645
+ /^child_process$/,
646
+ /^os$/,
647
+ /^path$/,
648
+ /^crypto$/,
649
+ /^http$/,
650
+ /^https$/,
651
+ /^dgram$/,
652
+ /^dns$/,
653
+ /^cluster$/,
654
+ /^readline$/,
655
+ /^repl$/,
656
+ /^tls$/,
657
+ /^vm$/,
658
+ /^worker_threads$/
659
+ ],
660
+ maxBundleSize: 512e3,
661
+ // 500KB
662
+ maxTransformTime: 5e3,
663
+ // 5s
664
+ noEval: true,
665
+ noDynamicImports: true,
666
+ noRequire: true,
667
+ allowedGlobals: [
668
+ "console",
669
+ "Math",
670
+ "JSON",
671
+ "Date",
672
+ "Array",
673
+ "Object",
674
+ "String",
675
+ "Number",
676
+ "Boolean",
677
+ "Promise",
678
+ "Map",
679
+ "Set",
680
+ "WeakMap",
681
+ "WeakSet",
682
+ "Symbol",
683
+ "Reflect",
684
+ "Proxy",
685
+ "Error",
686
+ "TypeError",
687
+ "RangeError",
688
+ "SyntaxError",
689
+ "ReferenceError",
690
+ "parseInt",
691
+ "parseFloat",
692
+ "isNaN",
693
+ "isFinite",
694
+ "encodeURI",
695
+ "encodeURIComponent",
696
+ "decodeURI",
697
+ "decodeURIComponent",
698
+ "setTimeout",
699
+ "clearTimeout",
700
+ "setInterval",
701
+ "clearInterval",
702
+ "atob",
703
+ "btoa",
704
+ "Intl",
705
+ "TextEncoder",
706
+ "TextDecoder",
707
+ "URL",
708
+ "URLSearchParams",
709
+ "Uint8Array",
710
+ "Int8Array",
711
+ "Uint16Array",
712
+ "Int16Array",
713
+ "Uint32Array",
714
+ "Int32Array",
715
+ "Float32Array",
716
+ "Float64Array",
717
+ "BigInt",
718
+ "BigInt64Array",
719
+ "BigUint64Array",
720
+ "ArrayBuffer",
721
+ "SharedArrayBuffer",
722
+ "DataView",
723
+ "queueMicrotask"
724
+ ]
725
+ };
726
+ var DEFAULT_BUNDLE_OPTIONS = {
727
+ sourceType: "auto",
728
+ format: "iife",
729
+ minify: false,
730
+ sourceMaps: false,
731
+ externals: ["react", "react-dom"],
732
+ jsx: {
733
+ runtime: "automatic",
734
+ importSource: "react"
735
+ },
736
+ target: "es2020",
737
+ globalName: "Widget",
738
+ skipCache: false
739
+ };
740
+ var DEFAULT_BUNDLER_OPTIONS = {
741
+ defaultSecurity: DEFAULT_SECURITY_POLICY,
742
+ cache: {
743
+ maxSize: 100,
744
+ ttl: 3e5,
745
+ // 5 minutes
746
+ disabled: false
747
+ },
748
+ verbose: false,
749
+ esbuildOptions: {}
750
+ };
751
+ var STATIC_HTML_CDN = {
752
+ /**
753
+ * ES modules from esm.sh (React 19, modern platforms)
754
+ */
755
+ esm: {
756
+ react: "https://esm.sh/react@19",
757
+ reactDom: "https://esm.sh/react-dom@19/client"
758
+ },
759
+ /**
760
+ * UMD builds from cdnjs (React 18.2, Claude only trusts cloudflare)
761
+ */
762
+ umd: {
763
+ react: "https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js",
764
+ reactDom: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"
765
+ },
766
+ /**
767
+ * Tailwind CSS from cdnjs (cloudflare) - works on all platforms
768
+ * Using CSS file instead of JS browser version to avoid style normalization issues
769
+ */
770
+ tailwind: "https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/3.4.1/tailwind.min.css",
771
+ /**
772
+ * Font CDN URLs
773
+ */
774
+ fonts: {
775
+ preconnect: ["https://fonts.googleapis.com", "https://fonts.gstatic.com"],
776
+ inter: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
777
+ }
778
+ };
779
+ function getCdnTypeForPlatform(platform) {
780
+ if (platform === "claude") return "umd";
781
+ return "esm";
782
+ }
783
+ var DEFAULT_STATIC_HTML_OPTIONS = {
784
+ sourceType: "auto",
785
+ targetPlatform: "auto",
786
+ minify: true,
787
+ skipCache: false,
788
+ rootId: "frontmcp-widget-root",
789
+ widgetAccessible: false,
790
+ externals: {
791
+ react: "cdn",
792
+ reactDom: "cdn",
793
+ tailwind: "cdn",
794
+ frontmcpUi: "inline"
795
+ },
796
+ // Universal mode defaults
797
+ universal: false,
798
+ contentType: "auto",
799
+ includeMarkdown: false,
800
+ includeMdx: false
801
+ };
802
+
803
+ // libs/ui/src/bundler/cache.ts
804
+ var BundlerCache = class {
805
+ cache = /* @__PURE__ */ new Map();
806
+ options;
807
+ stats = {
808
+ hits: 0,
809
+ misses: 0,
810
+ evictions: 0
811
+ };
812
+ constructor(options = {}) {
813
+ this.options = {
814
+ maxSize: options.maxSize ?? 100,
815
+ ttl: options.ttl ?? 3e5
816
+ };
817
+ }
818
+ /**
819
+ * Get a cached bundle result.
820
+ *
821
+ * @param key - Cache key (typically content hash)
822
+ * @returns Cached result or undefined if not found/expired
823
+ */
824
+ get(key) {
825
+ const entry = this.cache.get(key);
826
+ if (!entry) {
827
+ this.stats.misses++;
828
+ return void 0;
829
+ }
830
+ if (this.isExpired(entry)) {
831
+ this.cache.delete(key);
832
+ this.stats.misses++;
833
+ this.stats.evictions++;
834
+ return void 0;
835
+ }
836
+ entry.lastAccessedAt = Date.now();
837
+ entry.accessCount++;
838
+ this.stats.hits++;
839
+ this.cache.delete(key);
840
+ this.cache.set(key, entry);
841
+ return entry.result;
842
+ }
843
+ /**
844
+ * Store a bundle result in the cache.
845
+ *
846
+ * @param key - Cache key (typically content hash)
847
+ * @param result - Bundle result to cache
848
+ */
849
+ set(key, result) {
850
+ while (this.cache.size >= this.options.maxSize) {
851
+ this.evictOldest();
852
+ }
853
+ const now = Date.now();
854
+ const entry = {
855
+ result,
856
+ createdAt: now,
857
+ lastAccessedAt: now,
858
+ accessCount: 1
859
+ };
860
+ this.cache.set(key, entry);
861
+ }
862
+ /**
863
+ * Check if a key exists in the cache (and is not expired).
864
+ *
865
+ * @param key - Cache key to check
866
+ * @returns true if key exists and is not expired
867
+ */
868
+ has(key) {
869
+ const entry = this.cache.get(key);
870
+ if (!entry) return false;
871
+ if (this.isExpired(entry)) {
872
+ this.cache.delete(key);
873
+ this.stats.evictions++;
874
+ return false;
875
+ }
876
+ return true;
877
+ }
878
+ /**
879
+ * Delete a specific entry from the cache.
880
+ *
881
+ * @param key - Cache key to delete
882
+ * @returns true if the key was found and deleted
883
+ */
884
+ delete(key) {
885
+ return this.cache.delete(key);
886
+ }
887
+ /**
888
+ * Clear all entries from the cache.
889
+ */
890
+ clear() {
891
+ this.cache.clear();
892
+ this.stats = {
893
+ hits: 0,
894
+ misses: 0,
895
+ evictions: 0
896
+ };
897
+ }
898
+ /**
899
+ * Get cache statistics.
900
+ *
901
+ * @returns Current cache statistics
902
+ */
903
+ getStats() {
904
+ const total = this.stats.hits + this.stats.misses;
905
+ const hitRate = total > 0 ? this.stats.hits / total : 0;
906
+ let memoryUsage = 0;
907
+ for (const entry of this.cache.values()) {
908
+ memoryUsage += entry.result.size;
909
+ if (entry.result.map) {
910
+ memoryUsage += entry.result.map.length;
911
+ }
912
+ }
913
+ return {
914
+ size: this.cache.size,
915
+ hits: this.stats.hits,
916
+ misses: this.stats.misses,
917
+ hitRate,
918
+ evictions: this.stats.evictions,
919
+ memoryUsage
920
+ };
921
+ }
922
+ /**
923
+ * Remove expired entries from the cache.
924
+ *
925
+ * @returns Number of entries removed
926
+ */
927
+ cleanup() {
928
+ let removed = 0;
929
+ for (const [key, entry] of this.cache.entries()) {
930
+ if (this.isExpired(entry)) {
931
+ this.cache.delete(key);
932
+ removed++;
933
+ }
934
+ }
935
+ this.stats.evictions += removed;
936
+ return removed;
937
+ }
938
+ /**
939
+ * Get all cache keys.
940
+ *
941
+ * @returns Array of cache keys
942
+ */
943
+ keys() {
944
+ return Array.from(this.cache.keys());
945
+ }
946
+ /**
947
+ * Get the number of entries in the cache.
948
+ */
949
+ get size() {
950
+ return this.cache.size;
951
+ }
952
+ /**
953
+ * Check if an entry is expired.
954
+ */
955
+ isExpired(entry) {
956
+ return Date.now() - entry.createdAt > this.options.ttl;
957
+ }
958
+ /**
959
+ * Evict the oldest (least recently used) entry.
960
+ */
961
+ evictOldest() {
962
+ const oldestKey = this.cache.keys().next().value;
963
+ if (oldestKey !== void 0) {
964
+ this.cache.delete(oldestKey);
965
+ this.stats.evictions++;
966
+ }
967
+ }
968
+ };
969
+ function hashContent(content) {
970
+ let hash = 2166136261;
971
+ for (let i = 0; i < content.length; i++) {
972
+ hash ^= content.charCodeAt(i);
973
+ hash = Math.imul(hash, 16777619);
974
+ }
975
+ return (hash >>> 0).toString(16).padStart(8, "0");
976
+ }
977
+ function createCacheKey(source, options) {
978
+ const sourceHash = hashContent(source);
979
+ const optionsHash = hashContent(
980
+ JSON.stringify({
981
+ sourceType: options.sourceType,
982
+ format: options.format,
983
+ minify: options.minify,
984
+ externals: options.externals?.sort(),
985
+ target: options.target
986
+ })
987
+ );
988
+ return `${sourceHash}-${optionsHash}`;
989
+ }
990
+
991
+ // libs/ui/src/bundler/sandbox/policy.ts
992
+ var UNSAFE_PATTERNS = {
993
+ eval: /\beval\s*\(/g,
994
+ functionConstructor: /\bnew\s+Function\s*\(/g,
995
+ dynamicImport: /\bimport\s*\(/g,
996
+ require: /\brequire\s*\(/g,
997
+ processEnv: /\bprocess\.env\b/g,
998
+ globalThis: /\bglobalThis\b/g,
999
+ windowLocation: /\bwindow\.location\b/g,
1000
+ documentCookie: /\bdocument\.cookie\b/g,
1001
+ innerHTML: /\.innerHTML\s*=/g,
1002
+ outerHTML: /\.outerHTML\s*=/g,
1003
+ document_write: /\bdocument\.write\s*\(/g
1004
+ };
1005
+ function validateSource(source, policy = DEFAULT_SECURITY_POLICY) {
1006
+ const violations = [];
1007
+ if (policy.noEval !== false) {
1008
+ const evalMatches = [...source.matchAll(UNSAFE_PATTERNS.eval)];
1009
+ for (const match of evalMatches) {
1010
+ violations.push({
1011
+ type: "eval-usage",
1012
+ message: "eval() is not allowed for security reasons",
1013
+ location: getLocation(source, match.index ?? 0),
1014
+ value: match[0]
1015
+ });
1016
+ }
1017
+ const fnMatches = [...source.matchAll(UNSAFE_PATTERNS.functionConstructor)];
1018
+ for (const match of fnMatches) {
1019
+ violations.push({
1020
+ type: "eval-usage",
1021
+ message: "new Function() is not allowed for security reasons",
1022
+ location: getLocation(source, match.index ?? 0),
1023
+ value: match[0]
1024
+ });
1025
+ }
1026
+ }
1027
+ if (policy.noDynamicImports !== false) {
1028
+ const matches = [...source.matchAll(UNSAFE_PATTERNS.dynamicImport)];
1029
+ for (const match of matches) {
1030
+ violations.push({
1031
+ type: "dynamic-import",
1032
+ message: "Dynamic imports are not allowed for security reasons",
1033
+ location: getLocation(source, match.index ?? 0),
1034
+ value: match[0]
1035
+ });
1036
+ }
1037
+ }
1038
+ if (policy.noRequire !== false) {
1039
+ const matches = [...source.matchAll(UNSAFE_PATTERNS.require)];
1040
+ for (const match of matches) {
1041
+ violations.push({
1042
+ type: "require-usage",
1043
+ message: "require() is not allowed for security reasons",
1044
+ location: getLocation(source, match.index ?? 0),
1045
+ value: match[0]
1046
+ });
1047
+ }
1048
+ }
1049
+ const importViolations = validateImports(source, policy);
1050
+ violations.push(...importViolations);
1051
+ return violations;
1052
+ }
1053
+ function validateImports(source, policy = DEFAULT_SECURITY_POLICY) {
1054
+ const violations = [];
1055
+ const importPattern = /import\s+(?:(?:\{[^}]*\}|[\w*]+)\s+from\s+)?['"]([^'"]+)['"]/g;
1056
+ const imports = [];
1057
+ let match;
1058
+ while ((match = importPattern.exec(source)) !== null) {
1059
+ imports.push({ module: match[1], index: match.index });
1060
+ }
1061
+ const requirePattern = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
1062
+ while ((match = requirePattern.exec(source)) !== null) {
1063
+ imports.push({ module: match[1], index: match.index });
1064
+ }
1065
+ for (const imp of imports) {
1066
+ if (policy.blockedImports) {
1067
+ for (const blocked of policy.blockedImports) {
1068
+ if (blocked.test(imp.module)) {
1069
+ violations.push({
1070
+ type: "blocked-import",
1071
+ message: `Import '${imp.module}' is blocked by security policy`,
1072
+ location: getLocation(source, imp.index),
1073
+ value: imp.module
1074
+ });
1075
+ break;
1076
+ }
1077
+ }
1078
+ }
1079
+ if (policy.allowedImports && policy.allowedImports.length > 0) {
1080
+ const isAllowed = policy.allowedImports.some((pattern) => pattern.test(imp.module));
1081
+ if (!isAllowed) {
1082
+ const alreadyBlocked = violations.some((v) => v.type === "blocked-import" && v.value === imp.module);
1083
+ if (!alreadyBlocked) {
1084
+ violations.push({
1085
+ type: "disallowed-import",
1086
+ message: `Import '${imp.module}' is not in the allowed imports list`,
1087
+ location: getLocation(source, imp.index),
1088
+ value: imp.module
1089
+ });
1090
+ }
1091
+ }
1092
+ }
1093
+ }
1094
+ return violations;
1095
+ }
1096
+ function validateSize(size, policy = DEFAULT_SECURITY_POLICY) {
1097
+ const maxSize = policy.maxBundleSize ?? DEFAULT_SECURITY_POLICY.maxBundleSize ?? 512e3;
1098
+ if (size > maxSize) {
1099
+ return {
1100
+ type: "size-exceeded",
1101
+ message: `Bundle size (${formatBytes(size)}) exceeds maximum allowed (${formatBytes(maxSize)})`,
1102
+ value: String(size)
1103
+ };
1104
+ }
1105
+ return void 0;
1106
+ }
1107
+ function mergePolicy(userPolicy) {
1108
+ if (!userPolicy) {
1109
+ return { ...DEFAULT_SECURITY_POLICY };
1110
+ }
1111
+ return {
1112
+ allowedImports: userPolicy.allowedImports ?? DEFAULT_SECURITY_POLICY.allowedImports,
1113
+ blockedImports: userPolicy.blockedImports ?? DEFAULT_SECURITY_POLICY.blockedImports,
1114
+ maxBundleSize: userPolicy.maxBundleSize ?? DEFAULT_SECURITY_POLICY.maxBundleSize,
1115
+ maxTransformTime: userPolicy.maxTransformTime ?? DEFAULT_SECURITY_POLICY.maxTransformTime,
1116
+ noEval: userPolicy.noEval ?? DEFAULT_SECURITY_POLICY.noEval,
1117
+ noDynamicImports: userPolicy.noDynamicImports ?? DEFAULT_SECURITY_POLICY.noDynamicImports,
1118
+ noRequire: userPolicy.noRequire ?? DEFAULT_SECURITY_POLICY.noRequire,
1119
+ allowedGlobals: userPolicy.allowedGlobals ?? DEFAULT_SECURITY_POLICY.allowedGlobals
1120
+ };
1121
+ }
1122
+ function getLocation(source, index) {
1123
+ const lines = source.slice(0, index).split("\n");
1124
+ return {
1125
+ line: lines.length,
1126
+ column: lines[lines.length - 1].length + 1
1127
+ };
1128
+ }
1129
+ function formatBytes(bytes) {
1130
+ if (bytes < 1024) return `${bytes} B`;
1131
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1132
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1133
+ }
1134
+ var SecurityError = class extends Error {
1135
+ violations;
1136
+ constructor(message, violations) {
1137
+ super(message);
1138
+ this.name = "SecurityError";
1139
+ this.violations = violations;
1140
+ }
1141
+ };
1142
+ function throwOnViolations(violations) {
1143
+ if (violations.length > 0) {
1144
+ const message = violations.map((v) => v.message).join("; ");
1145
+ throw new SecurityError(`Security policy violation: ${message}`, violations);
1146
+ }
1147
+ }
1148
+
1149
+ // libs/ui/src/bundler/sandbox/enclave-adapter.ts
1150
+ import { Enclave } from "enclave-vm";
1151
+ var DEFAULT_ENCLAVE_OPTIONS = {
1152
+ securityLevel: "SECURE",
1153
+ timeout: 5e3,
1154
+ maxIterations: 1e4,
1155
+ validate: true,
1156
+ transform: true
1157
+ };
1158
+ var STRICT_SECURITY_BLOCKED_IMPORTS_THRESHOLD = 10;
1159
+ function mapSecurityLevel(policy) {
1160
+ if (policy?.blockedImports && policy.blockedImports.length > STRICT_SECURITY_BLOCKED_IMPORTS_THRESHOLD) {
1161
+ return "STRICT";
1162
+ }
1163
+ return "SECURE";
1164
+ }
1165
+ function createJSXRuntime(React) {
1166
+ const R = React;
1167
+ return {
1168
+ jsx: (type, props, key) => {
1169
+ const { children, ...rest } = props;
1170
+ return R.createElement(type, key ? { ...rest, key } : rest, children);
1171
+ },
1172
+ jsxs: (type, props, key) => {
1173
+ const { children, ...rest } = props;
1174
+ return R.createElement(type, key ? { ...rest, key } : rest, children);
1175
+ },
1176
+ jsxDEV: (type, props, key, _isStaticChildren, _source, _self) => {
1177
+ const { children, ...rest } = props;
1178
+ return R.createElement(type, key ? { ...rest, key } : rest, children);
1179
+ },
1180
+ Fragment: R.Fragment
1181
+ };
1182
+ }
1183
+ var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set([
1184
+ "process",
1185
+ "require",
1186
+ "__dirname",
1187
+ "__filename",
1188
+ "Buffer",
1189
+ "eval",
1190
+ "Function",
1191
+ "constructor",
1192
+ "global",
1193
+ "globalThis",
1194
+ "module",
1195
+ "exports",
1196
+ "__proto__"
1197
+ ]);
1198
+ function sanitizeGlobalKey(key) {
1199
+ return key.replace(/[^a-zA-Z0-9_$]/g, "_");
1200
+ }
1201
+ function buildGlobals(context) {
1202
+ const globals = {};
1203
+ if (context.React) {
1204
+ globals["React"] = context.React;
1205
+ }
1206
+ if (context.ReactDOM) {
1207
+ globals["ReactDOM"] = context.ReactDOM;
1208
+ }
1209
+ if (context.React) {
1210
+ const jsxRuntime = createJSXRuntime(context.React);
1211
+ globals["__jsx"] = jsxRuntime["jsx"];
1212
+ globals["__jsxs"] = jsxRuntime["jsxs"];
1213
+ globals["__jsxDEV"] = jsxRuntime["jsxDEV"];
1214
+ globals["Fragment"] = jsxRuntime["Fragment"];
1215
+ }
1216
+ if (context.modules) {
1217
+ for (const [key, value] of Object.entries(context.modules)) {
1218
+ const sanitizedKey = sanitizeGlobalKey(key);
1219
+ if (DANGEROUS_GLOBAL_KEYS.has(sanitizedKey)) {
1220
+ throw new ExecutionError(
1221
+ `Dangerous module key '${key}' (sanitized: '${sanitizedKey}') is not allowed in execution context`,
1222
+ { code: "SECURITY_VIOLATION" }
1223
+ );
1224
+ }
1225
+ globals[sanitizedKey] = value;
1226
+ }
1227
+ }
1228
+ if (context.globals) {
1229
+ for (const [key, value] of Object.entries(context.globals)) {
1230
+ if (DANGEROUS_GLOBAL_KEYS.has(key)) {
1231
+ throw new ExecutionError(`Dangerous global key '${key}' is not allowed in execution context`, {
1232
+ code: "SECURITY_VIOLATION"
1233
+ });
1234
+ }
1235
+ const sanitizedKey = sanitizeGlobalKey(key);
1236
+ if (DANGEROUS_GLOBAL_KEYS.has(sanitizedKey)) {
1237
+ throw new ExecutionError(
1238
+ `Dangerous global key '${key}' (sanitized: '${sanitizedKey}') is not allowed in execution context`,
1239
+ { code: "SECURITY_VIOLATION" }
1240
+ );
1241
+ }
1242
+ globals[sanitizedKey] = value;
1243
+ }
1244
+ }
1245
+ return globals;
1246
+ }
1247
+ function buildRequireFunction(context) {
1248
+ const normalizedContextModules = {};
1249
+ if (context.modules) {
1250
+ for (const [key, value] of Object.entries(context.modules)) {
1251
+ normalizedContextModules[key.toLowerCase()] = value;
1252
+ }
1253
+ }
1254
+ const modules = {
1255
+ react: context.React,
1256
+ "react-dom": context.ReactDOM,
1257
+ "react/jsx-runtime": context.React ? createJSXRuntime(context.React) : void 0,
1258
+ "react/jsx-dev-runtime": context.React ? createJSXRuntime(context.React) : void 0,
1259
+ ...normalizedContextModules
1260
+ };
1261
+ return (id) => {
1262
+ const normalizedId = id.toLowerCase();
1263
+ if (normalizedId in modules) {
1264
+ const mod = modules[normalizedId];
1265
+ if (mod === void 0) {
1266
+ throw new Error(`Module '${id}' is not available. Did you forget to provide it in the context?`);
1267
+ }
1268
+ return mod;
1269
+ }
1270
+ throw new Error(`Module '${id}' is not available in the sandbox environment`);
1271
+ };
1272
+ }
1273
+ async function executeCode(code, context = {}) {
1274
+ const consoleOutput = [];
1275
+ const globals = buildGlobals(context);
1276
+ globals["console"] = {
1277
+ log: (...args) => {
1278
+ consoleOutput.push(args.map(String).join(" "));
1279
+ },
1280
+ info: (...args) => {
1281
+ consoleOutput.push(`[INFO] ${args.map(String).join(" ")}`);
1282
+ },
1283
+ warn: (...args) => {
1284
+ consoleOutput.push(`[WARN] ${args.map(String).join(" ")}`);
1285
+ },
1286
+ error: (...args) => {
1287
+ consoleOutput.push(`[ERROR] ${args.map(String).join(" ")}`);
1288
+ },
1289
+ debug: (...args) => {
1290
+ consoleOutput.push(`[DEBUG] ${args.map(String).join(" ")}`);
1291
+ },
1292
+ trace: () => {
1293
+ },
1294
+ dir: () => {
1295
+ },
1296
+ table: () => {
1297
+ },
1298
+ group: () => {
1299
+ },
1300
+ groupEnd: () => {
1301
+ },
1302
+ time: () => {
1303
+ },
1304
+ timeEnd: () => {
1305
+ },
1306
+ assert: () => {
1307
+ },
1308
+ clear: () => {
1309
+ },
1310
+ count: () => {
1311
+ },
1312
+ countReset: () => {
1313
+ }
1314
+ };
1315
+ globals["require"] = buildRequireFunction(context);
1316
+ const enclave = new Enclave({
1317
+ ...DEFAULT_ENCLAVE_OPTIONS,
1318
+ timeout: context.timeout ?? DEFAULT_ENCLAVE_OPTIONS.timeout,
1319
+ maxIterations: context.maxIterations ?? DEFAULT_ENCLAVE_OPTIONS.maxIterations,
1320
+ securityLevel: mapSecurityLevel(context.security),
1321
+ globals,
1322
+ allowFunctionsInGlobals: true
1323
+ // Required for React components
1324
+ });
1325
+ try {
1326
+ const wrappedCode = `
1327
+ const module = { exports: {} };
1328
+ const exports = module.exports;
1329
+ const __filename = 'widget.js';
1330
+ const __dirname = '/';
1331
+ ${code}
1332
+ return module.exports;
1333
+ `;
1334
+ const result = await enclave.run(wrappedCode);
1335
+ if (!result.success) {
1336
+ const errorMessage = result.error?.message ?? "Execution failed";
1337
+ const errorCode = result.error?.code;
1338
+ if (errorCode === "TIMEOUT") {
1339
+ throw new ExecutionError(`Execution timed out after ${context.timeout ?? DEFAULT_ENCLAVE_OPTIONS.timeout}ms`, {
1340
+ code: "TIMEOUT"
1341
+ });
1342
+ }
1343
+ if (errorCode === "MAX_ITERATIONS") {
1344
+ throw new ExecutionError(
1345
+ `Maximum iterations exceeded (${context.maxIterations ?? DEFAULT_ENCLAVE_OPTIONS.maxIterations})`,
1346
+ {
1347
+ code: "MAX_ITERATIONS"
1348
+ }
1349
+ );
1350
+ }
1351
+ if (errorCode === "VALIDATION_ERROR") {
1352
+ throw new ExecutionError(`Security validation failed: ${errorMessage}`, { code: "SECURITY_VIOLATION" });
1353
+ }
1354
+ throw new ExecutionError(errorMessage, result.error);
1355
+ }
1356
+ return {
1357
+ exports: result.value,
1358
+ executionTime: result.stats.duration,
1359
+ consoleOutput: consoleOutput.length > 0 ? consoleOutput : void 0
1360
+ };
1361
+ } finally {
1362
+ enclave.dispose();
1363
+ }
1364
+ }
1365
+ async function executeDefault(code, context = {}) {
1366
+ const result = await executeCode(code, context);
1367
+ if ("default" in result.exports) {
1368
+ return result.exports.default;
1369
+ }
1370
+ const exportKeys = Object.keys(result.exports);
1371
+ if (exportKeys.length === 0) {
1372
+ throw new ExecutionError("Code did not export any values");
1373
+ }
1374
+ if (exportKeys.length === 1) {
1375
+ return result.exports[exportKeys[0]];
1376
+ }
1377
+ return result.exports;
1378
+ }
1379
+ var ExecutionError = class extends Error {
1380
+ /** Error code for categorization */
1381
+ code;
1382
+ constructor(message, cause) {
1383
+ super(message, { cause });
1384
+ this.name = "ExecutionError";
1385
+ if (cause && typeof cause === "object" && "code" in cause) {
1386
+ this.code = cause.code;
1387
+ }
1388
+ }
1389
+ };
1390
+ function isExecutionError(error) {
1391
+ return error instanceof ExecutionError;
1392
+ }
1393
+
1394
+ // libs/ui/src/bundler/bundler.ts
1395
+ import { escapeHtml } from "@frontmcp/uipack/utils";
1396
+
1397
+ // libs/ui/src/universal/types.ts
1398
+ var UNIVERSAL_CDN = {
1399
+ esm: {
1400
+ reactMarkdown: "https://esm.sh/react-markdown@9",
1401
+ mdxReact: "https://esm.sh/@mdx-js/react@3",
1402
+ remarkGfm: "https://esm.sh/remark-gfm@4"
1403
+ }
1404
+ // Note: These libraries are not available on cdnjs
1405
+ // For Claude, we use inline implementations
1406
+ };
1407
+ function detectContentType(source) {
1408
+ if (typeof source === "function") {
1409
+ return "react";
1410
+ }
1411
+ if (typeof source !== "string") {
1412
+ return "html";
1413
+ }
1414
+ const hasModuleSyntax = /^import\s+/m.test(source) || /^export\s+(default\s+)?/m.test(source) || /^const\s+\w+\s*=\s*\([^)]*\)\s*=>/m.test(source) || // Arrow function components
1415
+ /^function\s+\w+\s*\(/m.test(source);
1416
+ const hasJsxTags = /<[A-Z][a-zA-Z]*/.test(source);
1417
+ const hasMarkdown = /^#{1,6}\s/m.test(source) || /^\*\s/m.test(source) || /^-\s/m.test(source) || /^\d+\.\s/m.test(source);
1418
+ if (hasModuleSyntax && hasJsxTags) {
1419
+ return "react";
1420
+ }
1421
+ if (hasJsxTags && hasMarkdown && !hasModuleSyntax) {
1422
+ return "mdx";
1423
+ }
1424
+ if (hasMarkdown || /\*\*[^*]+\*\*/.test(source) || /\[[^\]]+\]\([^)]+\)/.test(source)) {
1425
+ return "markdown";
1426
+ }
1427
+ if (hasJsxTags && !hasModuleSyntax) {
1428
+ return "mdx";
1429
+ }
1430
+ return "html";
1431
+ }
1432
+
1433
+ // libs/ui/src/universal/cached-runtime.ts
1434
+ var RUNTIME_PLACEHOLDERS = {
1435
+ /** Placeholder for transpiled component code */
1436
+ COMPONENT_CODE: "/*__FRONTMCP_COMPONENT_CODE__*/",
1437
+ /** Placeholder for data injection */
1438
+ DATA_INJECTION: "/*__FRONTMCP_DATA_INJECTION__*/",
1439
+ /** Placeholder for custom components */
1440
+ CUSTOM_COMPONENTS: "/*__FRONTMCP_CUSTOM_COMPONENTS__*/"
1441
+ };
1442
+ var runtimeCache = /* @__PURE__ */ new Map();
1443
+ var DEFAULT_CACHE_CONFIG = {
1444
+ maxEntries: 10,
1445
+ ttl: 0
1446
+ // Forever by default
1447
+ };
1448
+ function generateCacheKey(options) {
1449
+ const securityKey = options.contentSecurity ? [
1450
+ options.contentSecurity.allowUnsafeLinks ? "unsafeLinks" : "",
1451
+ options.contentSecurity.allowInlineScripts ? "unsafeScripts" : "",
1452
+ options.contentSecurity.bypassSanitization ? "bypass" : ""
1453
+ ].filter(Boolean).join("+") || "secure" : "secure";
1454
+ return [
1455
+ options.cdnType,
1456
+ options.includeMarkdown ? "md" : "",
1457
+ options.includeMdx ? "mdx" : "",
1458
+ options.minify ? "min" : "",
1459
+ securityKey
1460
+ ].filter(Boolean).join(":");
1461
+ }
1462
+ function buildStoreRuntime() {
1463
+ return `
1464
+ // FrontMCP Store (Vendor)
1465
+ (function() {
1466
+ var state = {
1467
+ toolName: null,
1468
+ input: null,
1469
+ output: null,
1470
+ content: null,
1471
+ structuredContent: null,
1472
+ loading: false,
1473
+ error: null
1474
+ };
1475
+
1476
+ var listeners = new Set();
1477
+
1478
+ window.__frontmcp = {
1479
+ getState: function() { return state; },
1480
+ setState: function(partial) {
1481
+ state = Object.assign({}, state, partial);
1482
+ listeners.forEach(function(fn) { fn(); });
1483
+ },
1484
+ subscribe: function(fn) {
1485
+ listeners.add(fn);
1486
+ return function() { listeners.delete(fn); };
1487
+ },
1488
+ reset: function() {
1489
+ state = {
1490
+ toolName: null,
1491
+ input: null,
1492
+ output: null,
1493
+ content: null,
1494
+ structuredContent: null,
1495
+ loading: false,
1496
+ error: null
1497
+ };
1498
+ },
1499
+ context: state,
1500
+ setContext: function(ctx) {
1501
+ this.setState(ctx);
1502
+ }
1503
+ };
1504
+
1505
+ // React hooks
1506
+ window.useFrontMCPStore = function() {
1507
+ var store = window.__frontmcp;
1508
+ return React.useSyncExternalStore(
1509
+ store.subscribe,
1510
+ store.getState,
1511
+ store.getState
1512
+ );
1513
+ };
1514
+
1515
+ window.useToolOutput = function() {
1516
+ return window.useFrontMCPStore().output;
1517
+ };
1518
+
1519
+ window.useToolInput = function() {
1520
+ return window.useFrontMCPStore().input;
1521
+ };
1522
+
1523
+ window.useContent = function() {
1524
+ return window.useFrontMCPStore().content;
1525
+ };
1526
+ })();
1527
+ `;
1528
+ }
1529
+ function buildRequireShim() {
1530
+ return `
1531
+ // Module Require Shim (Vendor)
1532
+ (function() {
1533
+ window.__moduleCache = {};
1534
+ window.require = function(moduleName) {
1535
+ if (window.__moduleCache[moduleName]) {
1536
+ return window.__moduleCache[moduleName];
1537
+ }
1538
+
1539
+ var moduleMap = {
1540
+ 'react': function() { return window.React; },
1541
+ 'react-dom': function() { return window.ReactDOM; },
1542
+ 'react-dom/client': function() { return window.ReactDOM; },
1543
+ 'react/jsx-runtime': function() { return window.jsx_runtime_namespaceObject; },
1544
+ 'react/jsx-dev-runtime': function() { return window.jsx_runtime_namespaceObject; },
1545
+ '@frontmcp/ui': function() { return window.frontmcp_ui_namespaceObject; },
1546
+ '@frontmcp/ui/react': function() { return window.frontmcp_ui_namespaceObject; }
1547
+ };
1548
+
1549
+ var resolver = moduleMap[moduleName];
1550
+ if (resolver) {
1551
+ var mod = resolver();
1552
+ window.__moduleCache[moduleName] = mod;
1553
+ return mod;
1554
+ }
1555
+
1556
+ console.warn('[FrontMCP] Unknown module:', moduleName);
1557
+ return {};
1558
+ };
1559
+ })();
1560
+ `;
1561
+ }
1562
+ function buildInlineMarkdownParser(options) {
1563
+ const allowUnsafeLinks = options?.contentSecurity?.bypassSanitization || options?.contentSecurity?.allowUnsafeLinks;
1564
+ return `
1565
+ // Inline Markdown Parser (Vendor)
1566
+ (function() {
1567
+ // XSS protection settings (configured at build time)
1568
+ // Set to true if contentSecurity.allowUnsafeLinks or bypassSanitization is enabled
1569
+ var __allowUnsafeLinks = ${allowUnsafeLinks ? "true" : "false"};
1570
+
1571
+ // URL scheme validation to prevent XSS via javascript: URLs
1572
+ function isSafeUrl(url) {
1573
+ // If unsafe links are explicitly allowed, skip validation
1574
+ if (__allowUnsafeLinks) return true;
1575
+ if (!url) return false;
1576
+ var lower = url.toLowerCase().trim();
1577
+ return lower.startsWith('http://') ||
1578
+ lower.startsWith('https://') ||
1579
+ lower.startsWith('/') ||
1580
+ lower.startsWith('#') ||
1581
+ lower.startsWith('mailto:');
1582
+ }
1583
+
1584
+ function parseMarkdown(md) {
1585
+ var html = md;
1586
+ html = html.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1587
+ html = html.replace(/^######\\s+(.*)$/gm, '<h6>$1</h6>');
1588
+ html = html.replace(/^#####\\s+(.*)$/gm, '<h5>$1</h5>');
1589
+ html = html.replace(/^####\\s+(.*)$/gm, '<h4>$1</h4>');
1590
+ html = html.replace(/^###\\s+(.*)$/gm, '<h3>$1</h3>');
1591
+ html = html.replace(/^##\\s+(.*)$/gm, '<h2>$1</h2>');
1592
+ html = html.replace(/^#\\s+(.*)$/gm, '<h1>$1</h1>');
1593
+ html = html.replace(/\\*\\*\\*(.+?)\\*\\*\\*/g, '<strong><em>$1</em></strong>');
1594
+ html = html.replace(/\\*\\*(.+?)\\*\\*/g, '<strong>$1</strong>');
1595
+ html = html.replace(/\\*(.+?)\\*/g, '<em>$1</em>');
1596
+ html = html.replace(/\`([^\`]+)\`/g, '<code>$1</code>');
1597
+ // Links - validate URL scheme to prevent XSS (unless bypassed)
1598
+ html = html.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, function(match, text, url) {
1599
+ return isSafeUrl(url) ? '<a href="' + url + '">' + text + '</a>' : text;
1600
+ });
1601
+ html = html.replace(/^[-*]\\s+(.*)$/gm, '<li>$1</li>');
1602
+ html = html.replace(/\\n\\n+/g, '</p><p>');
1603
+ html = '<p>' + html + '</p>';
1604
+ return html;
1605
+ }
1606
+
1607
+ window.__frontmcp.parseMarkdown = parseMarkdown;
1608
+
1609
+ window.ReactMarkdown = function(props) {
1610
+ var html = parseMarkdown(props.children || '');
1611
+ return React.createElement('div', {
1612
+ className: 'frontmcp-markdown prose',
1613
+ dangerouslySetInnerHTML: { __html: html }
1614
+ });
1615
+ };
1616
+ })();
1617
+ `;
1618
+ }
1619
+ function buildRenderersRuntime(options) {
1620
+ const bypassSanitization = options?.contentSecurity?.bypassSanitization;
1621
+ const allowInlineScripts = bypassSanitization || options?.contentSecurity?.allowInlineScripts;
1622
+ return `
1623
+ // Universal Renderers (Vendor)
1624
+ (function() {
1625
+ var renderers = {};
1626
+
1627
+ // XSS protection settings (configured at build time)
1628
+ // Set to true if contentSecurity.allowInlineScripts or bypassSanitization is enabled
1629
+ var __allowInlineScripts = ${allowInlineScripts ? "true" : "false"};
1630
+
1631
+ renderers.html = {
1632
+ type: 'html',
1633
+ priority: 0,
1634
+ canHandle: function(c) { return c.type === 'html'; },
1635
+ render: function(c, ctx) {
1636
+ var html = c.source;
1637
+ // Apply XSS protection unless bypassed
1638
+ if (!__allowInlineScripts) {
1639
+ // Remove script tags and event handlers to prevent XSS
1640
+ html = html.replace(/<script[^>]*>[\\s\\S]*?<\\/script>/gi, '');
1641
+ html = html.replace(/\\s+on\\w+\\s*=/gi, ' data-removed-handler=');
1642
+ }
1643
+ return React.createElement('div', {
1644
+ className: 'frontmcp-html-content',
1645
+ dangerouslySetInnerHTML: { __html: html }
1646
+ });
1647
+ }
1648
+ };
1649
+
1650
+ renderers.markdown = {
1651
+ type: 'markdown',
1652
+ priority: 10,
1653
+ canHandle: function(c) {
1654
+ if (c.type === 'markdown') return true;
1655
+ if (typeof c.source !== 'string') return false;
1656
+ var s = c.source;
1657
+ return /^#{1,6}\\s/m.test(s) || /^[-*]\\s/m.test(s) || /\\*\\*[^*]+\\*\\*/.test(s);
1658
+ },
1659
+ render: function(c, ctx) {
1660
+ if (window.ReactMarkdown) {
1661
+ return React.createElement(window.ReactMarkdown, {
1662
+ children: c.source,
1663
+ components: Object.assign({}, ctx.components, c.components)
1664
+ });
1665
+ }
1666
+ var html = window.__frontmcp.parseMarkdown ? window.__frontmcp.parseMarkdown(c.source) : c.source;
1667
+ return React.createElement('div', {
1668
+ className: 'frontmcp-markdown prose',
1669
+ dangerouslySetInnerHTML: { __html: html }
1670
+ });
1671
+ }
1672
+ };
1673
+
1674
+ renderers.react = {
1675
+ type: 'react',
1676
+ priority: 30,
1677
+ canHandle: function(c) { return c.type === 'react' || typeof c.source === 'function'; },
1678
+ render: function(c, ctx) {
1679
+ var Component = c.source;
1680
+ var props = Object.assign({
1681
+ output: ctx.output,
1682
+ input: ctx.input,
1683
+ state: ctx.state,
1684
+ data: ctx.output // Alias for convenience
1685
+ }, c.props);
1686
+ return React.createElement(Component, props);
1687
+ }
1688
+ };
1689
+
1690
+ renderers.mdx = {
1691
+ type: 'mdx',
1692
+ priority: 20,
1693
+ canHandle: function(c) {
1694
+ if (c.type === 'mdx') return true;
1695
+ if (typeof c.source !== 'string') return false;
1696
+ var s = c.source;
1697
+ return /<[A-Z][a-zA-Z]*/.test(s) && /^#{1,6}\\s/m.test(s);
1698
+ },
1699
+ render: function(c, ctx) {
1700
+ if (typeof c.compiledContent === 'function') {
1701
+ var MDXContent = c.compiledContent;
1702
+ return React.createElement(MDXContent, {
1703
+ output: ctx.output,
1704
+ input: ctx.input,
1705
+ components: Object.assign({}, ctx.components, c.components)
1706
+ });
1707
+ }
1708
+ return React.createElement('div', { className: 'frontmcp-mdx-fallback' }, [
1709
+ React.createElement('div', {
1710
+ key: 'warn',
1711
+ className: 'bg-yellow-50 border border-yellow-200 rounded p-2 mb-2 text-sm text-yellow-800'
1712
+ }, 'MDX requires pre-compilation. Showing raw content.'),
1713
+ React.createElement('pre', {
1714
+ key: 'pre',
1715
+ className: 'bg-gray-100 p-4 rounded text-sm overflow-auto'
1716
+ }, c.source)
1717
+ ]);
1718
+ }
1719
+ };
1720
+
1721
+ var sortedRenderers = [renderers.react, renderers.mdx, renderers.markdown, renderers.html];
1722
+
1723
+ window.__frontmcp.detectRenderer = function(content) {
1724
+ if (content.type && renderers[content.type]) {
1725
+ return renderers[content.type];
1726
+ }
1727
+ for (var i = 0; i < sortedRenderers.length; i++) {
1728
+ if (sortedRenderers[i].canHandle(content)) {
1729
+ return sortedRenderers[i];
1730
+ }
1731
+ }
1732
+ return renderers.html;
1733
+ };
1734
+
1735
+ window.__frontmcp.renderContent = function(content, context) {
1736
+ var renderer = window.__frontmcp.detectRenderer(content);
1737
+ return renderer.render(content, context);
1738
+ };
1739
+
1740
+ window.__frontmcp.renderers = renderers;
1741
+ })();
1742
+ `;
1743
+ }
1744
+ function buildUIComponentsRuntime() {
1745
+ return `
1746
+ // UI Components (Vendor)
1747
+ (function() {
1748
+ window.Card = function(props) {
1749
+ var children = props.children;
1750
+ var title = props.title;
1751
+ var className = props.className || '';
1752
+ return React.createElement('div', {
1753
+ className: 'bg-white rounded-lg shadow border border-gray-200 overflow-hidden ' + className
1754
+ }, [
1755
+ title && React.createElement('div', {
1756
+ key: 'header',
1757
+ className: 'px-4 py-3 border-b border-gray-200 bg-gray-50'
1758
+ }, React.createElement('h3', { className: 'text-sm font-medium text-gray-900' }, title)),
1759
+ React.createElement('div', { key: 'body', className: 'p-4' }, children)
1760
+ ]);
1761
+ };
1762
+
1763
+ window.Badge = function(props) {
1764
+ var children = props.children;
1765
+ var variant = props.variant || 'default';
1766
+ var variantClasses = {
1767
+ default: 'bg-gray-100 text-gray-800',
1768
+ success: 'bg-green-100 text-green-800',
1769
+ warning: 'bg-yellow-100 text-yellow-800',
1770
+ error: 'bg-red-100 text-red-800',
1771
+ info: 'bg-blue-100 text-blue-800'
1772
+ };
1773
+ return React.createElement('span', {
1774
+ className: 'inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ' + (variantClasses[variant] || variantClasses.default)
1775
+ }, children);
1776
+ };
1777
+
1778
+ window.Button = function(props) {
1779
+ var children = props.children;
1780
+ var variant = props.variant || 'primary';
1781
+ var onClick = props.onClick;
1782
+ var disabled = props.disabled;
1783
+ var variantClasses = {
1784
+ primary: 'bg-blue-600 text-white hover:bg-blue-700',
1785
+ secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
1786
+ outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50',
1787
+ danger: 'bg-red-600 text-white hover:bg-red-700'
1788
+ };
1789
+ return React.createElement('button', {
1790
+ className: 'px-4 py-2 rounded-md text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 ' +
1791
+ (disabled ? 'opacity-50 cursor-not-allowed ' : '') +
1792
+ (variantClasses[variant] || variantClasses.primary),
1793
+ onClick: onClick,
1794
+ disabled: disabled
1795
+ }, children);
1796
+ };
1797
+
1798
+ // Export to namespace
1799
+ window.frontmcp_ui_namespaceObject = Object.assign({}, window.React || {}, {
1800
+ useToolOutput: window.useToolOutput,
1801
+ useToolInput: window.useToolInput,
1802
+ useMcpBridgeContext: function() { return window.__frontmcp.context; },
1803
+ useCallTool: function() { return function() { return Promise.resolve(null); }; },
1804
+ Card: window.Card,
1805
+ Badge: window.Badge,
1806
+ Button: window.Button
1807
+ });
1808
+ })();
1809
+ `;
1810
+ }
1811
+ function buildUniversalAppRuntime() {
1812
+ return `
1813
+ // Universal App (Vendor)
1814
+ (function() {
1815
+ var LoadingSpinner = function() {
1816
+ return React.createElement('div', {
1817
+ className: 'frontmcp-loading flex items-center justify-center min-h-[200px]'
1818
+ }, React.createElement('div', {
1819
+ className: 'frontmcp-spinner w-6 h-6 border-2 border-gray-200 border-t-blue-500 rounded-full animate-spin'
1820
+ }));
1821
+ };
1822
+
1823
+ var ErrorDisplay = function(props) {
1824
+ return React.createElement('div', {
1825
+ className: 'frontmcp-error bg-red-50 border border-red-200 rounded-lg p-4 text-red-800'
1826
+ }, [
1827
+ React.createElement('div', { key: 'title', className: 'font-medium' }, 'Error'),
1828
+ React.createElement('div', { key: 'msg', className: 'text-sm mt-1' }, props.error)
1829
+ ]);
1830
+ };
1831
+
1832
+ var EmptyState = function() {
1833
+ return React.createElement('div', {
1834
+ className: 'frontmcp-empty text-gray-500 text-center py-8'
1835
+ }, 'No content to display');
1836
+ };
1837
+
1838
+ window.__frontmcp.UniversalApp = function(props) {
1839
+ var state = window.useFrontMCPStore();
1840
+
1841
+ if (state.loading) {
1842
+ return props.fallback || React.createElement(LoadingSpinner);
1843
+ }
1844
+
1845
+ if (state.error) {
1846
+ var ErrorComp = props.errorFallback || ErrorDisplay;
1847
+ return React.createElement(ErrorComp, { error: state.error });
1848
+ }
1849
+
1850
+ var content = props.content || state.content;
1851
+
1852
+ if (!content) {
1853
+ return React.createElement(EmptyState);
1854
+ }
1855
+
1856
+ var context = {
1857
+ output: state.output,
1858
+ input: state.input,
1859
+ state: state,
1860
+ components: props.components || {}
1861
+ };
1862
+
1863
+ var rendered = window.__frontmcp.renderContent(content, context);
1864
+ return React.createElement('div', { className: 'frontmcp-content' }, rendered);
1865
+ };
1866
+
1867
+ window.__frontmcp.LoadingSpinner = LoadingSpinner;
1868
+ window.__frontmcp.ErrorDisplay = ErrorDisplay;
1869
+ window.__frontmcp.EmptyState = EmptyState;
1870
+ })();
1871
+ `;
1872
+ }
1873
+ function buildComponentWrapper() {
1874
+ return `
1875
+ // Component Execution (App Chunk)
1876
+ (function() {
1877
+ ${RUNTIME_PLACEHOLDERS.COMPONENT_CODE}
1878
+ })();
1879
+ `;
1880
+ }
1881
+ function buildDataInjectionWrapper() {
1882
+ return `
1883
+ // Data Injection (App Chunk)
1884
+ (function() {
1885
+ ${RUNTIME_PLACEHOLDERS.DATA_INJECTION}
1886
+ })();
1887
+ `;
1888
+ }
1889
+ function buildCustomComponentsWrapper() {
1890
+ return `
1891
+ // Custom Components (App Chunk)
1892
+ (function() {
1893
+ ${RUNTIME_PLACEHOLDERS.CUSTOM_COMPONENTS}
1894
+ })();
1895
+ `;
1896
+ }
1897
+ function buildCdnImports(options) {
1898
+ const parts = [];
1899
+ if (options.cdnType === "esm") {
1900
+ if (options.includeMarkdown) {
1901
+ parts.push(`
1902
+ <script type="module">
1903
+ import ReactMarkdown from '${UNIVERSAL_CDN.esm.reactMarkdown}';
1904
+ window.ReactMarkdown = ReactMarkdown;
1905
+ </script>`);
1906
+ }
1907
+ if (options.includeMdx) {
1908
+ parts.push(`
1909
+ <script type="module">
1910
+ import { MDXProvider } from '${UNIVERSAL_CDN.esm.mdxReact}';
1911
+ window.MDXProvider = MDXProvider;
1912
+ </script>`);
1913
+ }
1914
+ }
1915
+ return parts.join("\n");
1916
+ }
1917
+ function getCachedRuntime(options, config = {}) {
1918
+ const cacheKey = generateCacheKey(options);
1919
+ const cacheConfig = { ...DEFAULT_CACHE_CONFIG, ...config };
1920
+ const cached = runtimeCache.get(cacheKey);
1921
+ if (cached) {
1922
+ if (cacheConfig.ttl === 0 || Date.now() - cached.cachedAt < cacheConfig.ttl) {
1923
+ return {
1924
+ vendorScript: cached.script,
1925
+ appTemplate: buildAppTemplate(),
1926
+ cdnImports: cached.cdnImports,
1927
+ vendorSize: cached.size,
1928
+ cached: true,
1929
+ cacheKey
1930
+ };
1931
+ }
1932
+ runtimeCache.delete(cacheKey);
1933
+ }
1934
+ const vendorParts = [buildStoreRuntime(), buildRequireShim()];
1935
+ if (options.cdnType === "umd" || options.includeMarkdown) {
1936
+ vendorParts.push(buildInlineMarkdownParser(options));
1937
+ }
1938
+ vendorParts.push(buildRenderersRuntime(options));
1939
+ vendorParts.push(buildUIComponentsRuntime());
1940
+ vendorParts.push(buildUniversalAppRuntime());
1941
+ let vendorScript = vendorParts.join("\n");
1942
+ if (options.minify) {
1943
+ vendorScript = minifyScript(vendorScript);
1944
+ }
1945
+ const cdnImports = buildCdnImports(options);
1946
+ const entry = {
1947
+ script: vendorScript,
1948
+ cdnImports,
1949
+ size: vendorScript.length,
1950
+ cacheKey,
1951
+ cachedAt: Date.now()
1952
+ };
1953
+ if (runtimeCache.size >= cacheConfig.maxEntries) {
1954
+ const oldestKey = runtimeCache.keys().next().value;
1955
+ if (oldestKey) {
1956
+ runtimeCache.delete(oldestKey);
1957
+ }
1958
+ }
1959
+ runtimeCache.set(cacheKey, entry);
1960
+ return {
1961
+ vendorScript,
1962
+ appTemplate: buildAppTemplate(),
1963
+ cdnImports,
1964
+ vendorSize: vendorScript.length,
1965
+ cached: false,
1966
+ cacheKey
1967
+ };
1968
+ }
1969
+ function buildAppTemplate() {
1970
+ return [buildCustomComponentsWrapper(), buildComponentWrapper(), buildDataInjectionWrapper()].join("\n");
1971
+ }
1972
+ function minifyScript(script) {
1973
+ return script.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "").replace(/\n\s*\n/g, "\n").replace(/^\s+/gm, "").trim();
1974
+ }
1975
+ function buildAppScript(appTemplate, componentCode, dataInjection, customComponents = "") {
1976
+ return appTemplate.replace(RUNTIME_PLACEHOLDERS.CUSTOM_COMPONENTS, customComponents || "// No custom components").replace(RUNTIME_PLACEHOLDERS.COMPONENT_CODE, componentCode || "// No component code").replace(RUNTIME_PLACEHOLDERS.DATA_INJECTION, dataInjection);
1977
+ }
1978
+ function buildDataInjectionCode(toolName, input, output, structuredContent, contentType, source, hasComponent) {
1979
+ const safeJson = (value) => {
1980
+ try {
1981
+ return JSON.stringify(value);
1982
+ } catch {
1983
+ return "null";
1984
+ }
1985
+ };
1986
+ if (hasComponent) {
1987
+ return `
1988
+ window.__frontmcp.setState({
1989
+ toolName: ${safeJson(toolName)},
1990
+ input: ${safeJson(input ?? null)},
1991
+ output: ${safeJson(output ?? null)},
1992
+ structuredContent: ${safeJson(structuredContent ?? null)},
1993
+ content: {
1994
+ type: 'react',
1995
+ source: window.__frontmcp_component
1996
+ },
1997
+ loading: false,
1998
+ error: null
1999
+ });`;
2000
+ }
2001
+ return `
2002
+ window.__frontmcp.setState({
2003
+ toolName: ${safeJson(toolName)},
2004
+ input: ${safeJson(input ?? null)},
2005
+ output: ${safeJson(output ?? null)},
2006
+ structuredContent: ${safeJson(structuredContent ?? null)},
2007
+ content: {
2008
+ type: ${safeJson(contentType)},
2009
+ source: ${safeJson(source)}
2010
+ },
2011
+ loading: false,
2012
+ error: null
2013
+ });`;
2014
+ }
2015
+ function buildComponentCode(transpiledCode) {
2016
+ return `
2017
+ // CommonJS module shim
2018
+ var module = { exports: {} };
2019
+ var exports = module.exports;
2020
+
2021
+ // Execute transpiled component
2022
+ ${transpiledCode}
2023
+
2024
+ // Capture component
2025
+ window.__frontmcp_component = module.exports.default || module.exports;`;
2026
+ }
2027
+
2028
+ // libs/ui/src/bundler/bundler.ts
2029
+ var esbuildTransform = null;
2030
+ async function loadEsbuild() {
2031
+ if (esbuildTransform !== null) {
2032
+ return esbuildTransform;
2033
+ }
2034
+ try {
2035
+ const esbuild = await import("esbuild");
2036
+ esbuildTransform = esbuild.transform;
2037
+ return esbuildTransform;
2038
+ } catch {
2039
+ try {
2040
+ const swc = await import("@swc/core");
2041
+ esbuildTransform = async (source, options) => {
2042
+ const opts = options;
2043
+ const result = await swc.transform(source, {
2044
+ jsc: {
2045
+ parser: {
2046
+ syntax: "typescript",
2047
+ tsx: opts.loader === "tsx" || opts.loader === "jsx"
2048
+ },
2049
+ transform: {
2050
+ react: {
2051
+ runtime: "automatic",
2052
+ development: false
2053
+ }
2054
+ },
2055
+ target: "es2020",
2056
+ minify: opts.minify ? { compress: true, mangle: true } : void 0
2057
+ },
2058
+ module: {
2059
+ type: "commonjs"
2060
+ },
2061
+ sourceMaps: opts.sourcemap ? true : false
2062
+ });
2063
+ return { code: result.code, map: result.map };
2064
+ };
2065
+ return esbuildTransform;
2066
+ } catch {
2067
+ console.warn(
2068
+ "[@frontmcp/ui/bundler] Neither esbuild nor @swc/core available. Install esbuild for best performance: npm install esbuild"
2069
+ );
2070
+ return null;
2071
+ }
2072
+ }
2073
+ }
2074
+ function sanitizeRootId(rootId) {
2075
+ const safeId = rootId.replace(/[^a-zA-Z0-9_-]/g, "");
2076
+ if (safeId !== rootId) {
2077
+ console.warn("[FrontMCP] rootId sanitized:", { original: rootId, sanitized: safeId });
2078
+ }
2079
+ return safeId || "frontmcp-root";
2080
+ }
2081
+ function sanitizeCss(css) {
2082
+ return css.replace(/<\/style>/gi, "\\3c/style\\3e");
2083
+ }
2084
+ var InMemoryBundler = class {
2085
+ cache;
2086
+ options;
2087
+ defaultSecurity;
2088
+ constructor(options = {}) {
2089
+ this.options = {
2090
+ ...DEFAULT_BUNDLER_OPTIONS,
2091
+ ...options,
2092
+ cache: {
2093
+ ...DEFAULT_BUNDLER_OPTIONS.cache,
2094
+ ...options.cache
2095
+ }
2096
+ };
2097
+ this.cache = new BundlerCache({
2098
+ maxSize: this.options.cache.maxSize,
2099
+ ttl: this.options.cache.ttl
2100
+ });
2101
+ this.defaultSecurity = mergePolicy(options.defaultSecurity);
2102
+ }
2103
+ /**
2104
+ * Bundle source code.
2105
+ *
2106
+ * @param options - Bundle options
2107
+ * @returns Bundle result
2108
+ */
2109
+ async bundle(options) {
2110
+ const startTime = performance.now();
2111
+ const opts = this.mergeOptions(options);
2112
+ if (!opts.skipCache && !this.options.cache.disabled) {
2113
+ const cacheKey = options.cacheKey ?? createCacheKey(options.source, opts);
2114
+ const cached = this.cache.get(cacheKey);
2115
+ if (cached) {
2116
+ return {
2117
+ ...cached,
2118
+ cached: true,
2119
+ metrics: {
2120
+ ...cached.metrics,
2121
+ cacheTime: performance.now() - startTime
2122
+ }
2123
+ };
2124
+ }
2125
+ }
2126
+ const security = mergePolicy(options.security ?? this.defaultSecurity);
2127
+ const violations = validateSource(options.source, security);
2128
+ throwOnViolations(violations);
2129
+ const sourceType = opts.sourceType === "auto" ? this.detectSourceType(options.source) : opts.sourceType;
2130
+ const transformStart = performance.now();
2131
+ const transformed = await this.transform(options.source, sourceType, opts);
2132
+ const transformTime = performance.now() - transformStart;
2133
+ const sizeViolation = validateSize(transformed.code.length, security);
2134
+ if (sizeViolation) {
2135
+ throwOnViolations([sizeViolation]);
2136
+ }
2137
+ const hash = hashContent(transformed.code);
2138
+ const result = {
2139
+ code: transformed.code,
2140
+ hash,
2141
+ cached: false,
2142
+ size: transformed.code.length,
2143
+ map: transformed.map,
2144
+ metrics: {
2145
+ transformTime,
2146
+ bundleTime: 0,
2147
+ // No separate bundle step for transform-only
2148
+ totalTime: performance.now() - startTime
2149
+ },
2150
+ sourceType,
2151
+ format: opts.format
2152
+ };
2153
+ if (!this.options.cache.disabled) {
2154
+ const cacheKey = options.cacheKey ?? createCacheKey(options.source, opts);
2155
+ this.cache.set(cacheKey, result);
2156
+ }
2157
+ return result;
2158
+ }
2159
+ /**
2160
+ * Bundle and execute for SSR.
2161
+ *
2162
+ * @param options - SSR bundle options
2163
+ * @returns SSR result with rendered HTML
2164
+ */
2165
+ async bundleSSR(options) {
2166
+ const startTime = performance.now();
2167
+ const bundleResult = await this.bundle({
2168
+ ...options,
2169
+ format: "cjs"
2170
+ // CommonJS for execution
2171
+ });
2172
+ let React;
2173
+ let ReactDOMServer;
2174
+ try {
2175
+ React = await import("react");
2176
+ ReactDOMServer = await import("react-dom/server");
2177
+ } catch {
2178
+ throw new Error("React and react-dom/server are required for SSR. Install them: npm install react react-dom");
2179
+ }
2180
+ const renderStart = performance.now();
2181
+ const Component = await executeDefault(bundleResult.code, {
2182
+ React,
2183
+ security: mergePolicy(options.security ?? this.defaultSecurity)
2184
+ });
2185
+ let html;
2186
+ try {
2187
+ const element = React.createElement(Component, options.context ?? {});
2188
+ html = ReactDOMServer.renderToString(element);
2189
+ } catch (error) {
2190
+ throw new ExecutionError(
2191
+ `SSR rendering failed: ${error instanceof Error ? error.message : String(error)}`,
2192
+ error
2193
+ );
2194
+ }
2195
+ const renderTime = performance.now() - renderStart;
2196
+ let hydrationScript;
2197
+ if (options.includeHydration) {
2198
+ hydrationScript = this.buildHydrationScript(bundleResult.code, options.context);
2199
+ }
2200
+ return {
2201
+ ...bundleResult,
2202
+ html,
2203
+ hydrationScript,
2204
+ metrics: {
2205
+ ...bundleResult.metrics,
2206
+ totalTime: performance.now() - startTime
2207
+ },
2208
+ ssrMetrics: {
2209
+ renderTime
2210
+ }
2211
+ };
2212
+ }
2213
+ /**
2214
+ * Bundle and execute code, returning the exports.
2215
+ *
2216
+ * @param options - Bundle options
2217
+ * @param context - Execution context
2218
+ * @returns Exported value
2219
+ */
2220
+ async bundleAndExecute(options, context) {
2221
+ const result = await this.bundle({
2222
+ ...options,
2223
+ format: "cjs"
2224
+ // CommonJS for execution
2225
+ });
2226
+ let React;
2227
+ try {
2228
+ React = await import("react");
2229
+ } catch {
2230
+ }
2231
+ return executeDefault(result.code, {
2232
+ React,
2233
+ globals: context,
2234
+ security: mergePolicy(options.security ?? this.defaultSecurity)
2235
+ });
2236
+ }
2237
+ /**
2238
+ * Bundle a component to a self-contained static HTML document.
2239
+ *
2240
+ * Creates a complete HTML page with:
2241
+ * - React runtime (CDN or inline based on platform)
2242
+ * - FrontMCP UI hooks and components (always inline)
2243
+ * - Tool data injection (input/output)
2244
+ * - Transpiled component code
2245
+ * - Client-side rendering via createRoot
2246
+ *
2247
+ * @param options - Static HTML options
2248
+ * @returns Static HTML result with complete document
2249
+ *
2250
+ * @example
2251
+ * ```typescript
2252
+ * const result = await bundler.bundleToStaticHTML({
2253
+ * source: `
2254
+ * import { Card, useToolOutput } from '@frontmcp/ui/react';
2255
+ * export default function Weather() {
2256
+ * const output = useToolOutput();
2257
+ * return <Card title="Weather">{output?.temperature}°F</Card>;
2258
+ * }
2259
+ * `,
2260
+ * toolName: 'get_weather',
2261
+ * output: { temperature: 72 },
2262
+ * });
2263
+ *
2264
+ * // result.html contains the complete HTML document
2265
+ * ```
2266
+ */
2267
+ async bundleToStaticHTML(options) {
2268
+ const startTime = performance.now();
2269
+ const opts = this.mergeStaticHTMLOptions(options);
2270
+ const platform = opts.targetPlatform === "auto" ? "generic" : opts.targetPlatform;
2271
+ const cdnType = getCdnTypeForPlatform(platform);
2272
+ if (opts.universal) {
2273
+ return this.bundleToStaticHTMLUniversal(options, opts, platform, cdnType, startTime);
2274
+ }
2275
+ const bundleResult = await this.bundle({
2276
+ source: options.source,
2277
+ sourceType: opts.sourceType,
2278
+ format: "cjs",
2279
+ minify: opts.minify,
2280
+ sourceMaps: false,
2281
+ externals: ["react", "react-dom", "react/jsx-runtime", "@frontmcp/ui", "@frontmcp/ui/react"],
2282
+ security: opts.security,
2283
+ skipCache: opts.skipCache
2284
+ });
2285
+ const head = this.buildStaticHTMLHead({ externals: opts.externals, customCss: opts.customCss });
2286
+ const reactRuntime = this.buildReactRuntimeScripts(opts.externals, platform, cdnType);
2287
+ const frontmcpRuntime = this.buildFrontMCPRuntime();
2288
+ const dataScript = this.buildDataInjectionScript(opts.toolName, opts.input, opts.output, opts.structuredContent);
2289
+ const componentScript = this.buildComponentRenderScript(bundleResult.code, opts.rootId, cdnType);
2290
+ const html = this.assembleStaticHTML({
2291
+ title: opts.title || `${opts.toolName} - Widget`,
2292
+ head,
2293
+ reactRuntime,
2294
+ frontmcpRuntime,
2295
+ dataScript,
2296
+ componentScript,
2297
+ rootId: opts.rootId,
2298
+ cdnType
2299
+ });
2300
+ const hash = hashContent(html);
2301
+ return {
2302
+ html,
2303
+ componentCode: bundleResult.code,
2304
+ metrics: {
2305
+ ...bundleResult.metrics,
2306
+ totalTime: performance.now() - startTime
2307
+ },
2308
+ hash,
2309
+ size: html.length,
2310
+ cached: bundleResult.cached,
2311
+ sourceType: bundleResult.sourceType,
2312
+ targetPlatform: platform
2313
+ };
2314
+ }
2315
+ /**
2316
+ * Bundle to static HTML with universal rendering mode.
2317
+ * Uses the universal renderer that can handle multiple content types.
2318
+ *
2319
+ * Optimization: Uses cached runtime (vendor chunk) to avoid rebuilding
2320
+ * static code on every request. Only the user's component is transpiled.
2321
+ */
2322
+ async bundleToStaticHTMLUniversal(options, opts, platform, cdnType, startTime) {
2323
+ let contentType;
2324
+ const rawContentType = options.contentType ?? "auto";
2325
+ if (rawContentType === "auto") {
2326
+ contentType = detectContentType(options.source);
2327
+ } else {
2328
+ contentType = rawContentType;
2329
+ }
2330
+ let transpiledCode = null;
2331
+ let transformTime = 0;
2332
+ if (contentType === "react") {
2333
+ const bundleResult = await this.bundle({
2334
+ source: options.source,
2335
+ sourceType: opts.sourceType,
2336
+ format: "cjs",
2337
+ minify: opts.minify,
2338
+ sourceMaps: false,
2339
+ externals: ["react", "react-dom", "react/jsx-runtime", "@frontmcp/ui", "@frontmcp/ui/react"],
2340
+ security: opts.security,
2341
+ skipCache: opts.skipCache
2342
+ });
2343
+ transpiledCode = bundleResult.code;
2344
+ transformTime = bundleResult.metrics.transformTime;
2345
+ }
2346
+ const cachedRuntime = getCachedRuntime({
2347
+ cdnType,
2348
+ includeMarkdown: opts.includeMarkdown || contentType === "markdown",
2349
+ includeMdx: opts.includeMdx || contentType === "mdx",
2350
+ minify: opts.minify
2351
+ });
2352
+ const componentCodeStr = transpiledCode ? buildComponentCode(transpiledCode) : "";
2353
+ const dataInjectionStr = buildDataInjectionCode(
2354
+ opts.toolName,
2355
+ opts.input,
2356
+ opts.output,
2357
+ opts.structuredContent,
2358
+ contentType,
2359
+ transpiledCode ? null : options.source,
2360
+ // Pass source only if not a component
2361
+ transpiledCode !== null
2362
+ );
2363
+ const appScript = buildAppScript(
2364
+ cachedRuntime.appTemplate,
2365
+ componentCodeStr,
2366
+ dataInjectionStr,
2367
+ opts.customComponents ?? ""
2368
+ );
2369
+ const head = this.buildStaticHTMLHead({ externals: opts.externals, customCss: opts.customCss });
2370
+ const reactRuntime = this.buildReactRuntimeScripts(opts.externals, platform, cdnType);
2371
+ const renderScript = this.buildUniversalRenderScript(opts.rootId, cdnType);
2372
+ const html = this.assembleUniversalStaticHTMLCached({
2373
+ title: opts.title || `${opts.toolName} - Widget`,
2374
+ head,
2375
+ reactRuntime,
2376
+ cdnImports: cachedRuntime.cdnImports,
2377
+ vendorScript: cachedRuntime.vendorScript,
2378
+ appScript,
2379
+ renderScript,
2380
+ rootId: opts.rootId,
2381
+ cdnType
2382
+ });
2383
+ const hash = hashContent(html);
2384
+ return {
2385
+ html,
2386
+ componentCode: transpiledCode ?? appScript,
2387
+ metrics: {
2388
+ transformTime,
2389
+ bundleTime: 0,
2390
+ totalTime: performance.now() - startTime,
2391
+ cacheTime: cachedRuntime.cached ? 0 : void 0
2392
+ },
2393
+ hash,
2394
+ size: html.length,
2395
+ cached: cachedRuntime.cached,
2396
+ sourceType: opts.sourceType === "auto" ? this.detectSourceType(options.source) : opts.sourceType,
2397
+ targetPlatform: platform,
2398
+ universal: true,
2399
+ contentType
2400
+ };
2401
+ }
2402
+ /**
2403
+ * Assemble the complete universal static HTML document using cached runtime.
2404
+ *
2405
+ * For ESM mode (OpenAI), scripts must wait for React to load asynchronously.
2406
+ * For UMD mode (Claude), scripts can execute synchronously.
2407
+ */
2408
+ assembleUniversalStaticHTMLCached(parts) {
2409
+ if (parts.cdnType === "umd") {
2410
+ return `<!DOCTYPE html>
2411
+ <html lang="en">
2412
+ <head>
2413
+ <title>${escapeHtml(parts.title)}</title>
2414
+ ${parts.head}
2415
+ ${parts.reactRuntime}
2416
+ ${parts.cdnImports}
2417
+ <!-- Vendor Runtime (Cached) -->
2418
+ <script>
2419
+ ${parts.vendorScript}
2420
+ </script>
2421
+ <!-- App Script (User Component) -->
2422
+ <script>
2423
+ ${parts.appScript}
2424
+ </script>
2425
+ </head>
2426
+ <body>
2427
+ <div id="${parts.rootId}" class="frontmcp-loading">
2428
+ <div class="frontmcp-spinner"></div>
2429
+ </div>
2430
+ ${parts.renderScript}
2431
+ </body>
2432
+ </html>`;
2433
+ } else {
2434
+ return `<!DOCTYPE html>
2435
+ <html lang="en">
2436
+ <head>
2437
+ <title>${escapeHtml(parts.title)}</title>
2438
+ ${parts.head}
2439
+ ${parts.reactRuntime}
2440
+ ${parts.cdnImports}
2441
+ </head>
2442
+ <body>
2443
+ <div id="${parts.rootId}" class="frontmcp-loading">
2444
+ <div class="frontmcp-spinner"></div>
2445
+ </div>
2446
+ <!-- Scripts wait for React to load (ESM is async) -->
2447
+ <script type="module">
2448
+ // Wait for React to be ready
2449
+ function initFrontMCP() {
2450
+ // Vendor Runtime (Cached)
2451
+ ${parts.vendorScript}
2452
+
2453
+ // App Script (User Component)
2454
+ ${parts.appScript}
2455
+
2456
+ // Render the app
2457
+ var container = document.getElementById('${parts.rootId}');
2458
+ if (container && window.ReactDOM && window.ReactDOM.createRoot && window.__frontmcp.UniversalApp) {
2459
+ var root = window.ReactDOM.createRoot(container);
2460
+ root.render(React.createElement(window.__frontmcp.UniversalApp));
2461
+ }
2462
+ }
2463
+
2464
+ if (window.__reactReady) {
2465
+ initFrontMCP();
2466
+ } else {
2467
+ window.addEventListener('react:ready', initFrontMCP);
2468
+ }
2469
+ </script>
2470
+ </body>
2471
+ </html>`;
2472
+ }
2473
+ }
2474
+ /**
2475
+ * Build the component script for transpiled React/MDX content.
2476
+ * Wraps CommonJS code with module/exports shim to capture the component.
2477
+ */
2478
+ buildUniversalComponentScript(transpiledCode, cdnType) {
2479
+ const wrappedCode = `
2480
+ // CommonJS module shim
2481
+ var module = { exports: {} };
2482
+ var exports = module.exports;
2483
+
2484
+ // Execute transpiled component code (CommonJS format)
2485
+ ${transpiledCode}
2486
+
2487
+ // Capture the component export
2488
+ window.__frontmcp_component = module.exports.default || module.exports;
2489
+ `;
2490
+ if (cdnType === "umd") {
2491
+ return `
2492
+ <!-- Universal Component Script (transpiled) -->
2493
+ <script>
2494
+ (function() {
2495
+ ${wrappedCode}
2496
+ })();
2497
+ </script>`;
2498
+ } else {
2499
+ return `
2500
+ <!-- Universal Component Script (transpiled, ESM) -->
2501
+ <script type="module">
2502
+ function loadComponent() {
2503
+ ${wrappedCode}
2504
+ }
2505
+
2506
+ if (window.__reactReady) {
2507
+ loadComponent();
2508
+ } else {
2509
+ window.addEventListener('react:ready', loadComponent);
2510
+ }
2511
+ </script>`;
2512
+ }
2513
+ }
2514
+ /**
2515
+ * Build the universal runtime script section.
2516
+ */
2517
+ buildUniversalRuntimeScript(runtimeScript) {
2518
+ return `
2519
+ <!-- Universal Runtime -->
2520
+ <script>
2521
+ ${runtimeScript}
2522
+ </script>`;
2523
+ }
2524
+ /**
2525
+ * Build data injection script for universal mode.
2526
+ */
2527
+ buildUniversalDataScript(toolName, input, output, structuredContent, contentType, source, hasTranspiledComponent = false) {
2528
+ const safeJson = (value) => {
2529
+ try {
2530
+ return JSON.stringify(value);
2531
+ } catch {
2532
+ return "null";
2533
+ }
2534
+ };
2535
+ if (hasTranspiledComponent) {
2536
+ return `
2537
+ <!-- Universal Data Injection (React Component) -->
2538
+ <script>
2539
+ window.__frontmcp.setState({
2540
+ toolName: ${safeJson(toolName)},
2541
+ input: ${safeJson(input ?? null)},
2542
+ output: ${safeJson(output ?? null)},
2543
+ structuredContent: ${safeJson(structuredContent ?? null)},
2544
+ content: {
2545
+ type: 'react',
2546
+ source: window.__frontmcp_component
2547
+ },
2548
+ loading: false,
2549
+ error: null
2550
+ });
2551
+ </script>`;
2552
+ }
2553
+ const escapedSource = JSON.stringify(source);
2554
+ return `
2555
+ <!-- Universal Data Injection -->
2556
+ <script>
2557
+ window.__frontmcp.setState({
2558
+ toolName: ${safeJson(toolName)},
2559
+ input: ${safeJson(input ?? null)},
2560
+ output: ${safeJson(output ?? null)},
2561
+ structuredContent: ${safeJson(structuredContent ?? null)},
2562
+ content: {
2563
+ type: ${safeJson(contentType)},
2564
+ source: ${escapedSource}
2565
+ },
2566
+ loading: false,
2567
+ error: null
2568
+ });
2569
+ </script>`;
2570
+ }
2571
+ /**
2572
+ * Build the universal render script.
2573
+ */
2574
+ buildUniversalRenderScript(rootId, cdnType) {
2575
+ if (cdnType === "umd") {
2576
+ return `
2577
+ <!-- Universal Render Script (UMD - synchronous) -->
2578
+ <script>
2579
+ (function() {
2580
+ var container = document.getElementById('${rootId}');
2581
+ if (container && window.ReactDOM && window.ReactDOM.createRoot && window.__frontmcp.UniversalApp) {
2582
+ var root = window.ReactDOM.createRoot(container);
2583
+ root.render(React.createElement(window.__frontmcp.UniversalApp));
2584
+ } else if (container && window.ReactDOM && window.ReactDOM.render && window.__frontmcp.UniversalApp) {
2585
+ window.ReactDOM.render(
2586
+ React.createElement(window.__frontmcp.UniversalApp),
2587
+ container
2588
+ );
2589
+ }
2590
+ })();
2591
+ </script>`;
2592
+ } else {
2593
+ return `
2594
+ <!-- Universal Render Script (ESM - waits for React) -->
2595
+ <script type="module">
2596
+ function renderUniversalApp() {
2597
+ var container = document.getElementById('${rootId}');
2598
+ if (container && window.ReactDOM && window.ReactDOM.createRoot && window.__frontmcp.UniversalApp) {
2599
+ var root = window.ReactDOM.createRoot(container);
2600
+ root.render(React.createElement(window.__frontmcp.UniversalApp));
2601
+ }
2602
+ }
2603
+
2604
+ if (window.__reactReady) {
2605
+ renderUniversalApp();
2606
+ } else {
2607
+ window.addEventListener('react:ready', renderUniversalApp);
2608
+ }
2609
+ </script>`;
2610
+ }
2611
+ }
2612
+ /**
2613
+ * Assemble the complete universal static HTML document.
2614
+ */
2615
+ assembleUniversalStaticHTML(parts) {
2616
+ return `<!DOCTYPE html>
2617
+ <html lang="en">
2618
+ <head>
2619
+ <title>${escapeHtml(parts.title)}</title>
2620
+ ${parts.head}
2621
+ ${parts.reactRuntime}
2622
+ ${parts.frontmcpRuntime ?? ""}
2623
+ ${parts.cdnImports}
2624
+ ${parts.universalRuntimeScript}
2625
+ ${parts.componentScript ?? ""}
2626
+ ${parts.dataScript}
2627
+ </head>
2628
+ <body>
2629
+ <div id="${parts.rootId}" class="frontmcp-loading">
2630
+ <div class="frontmcp-spinner"></div>
2631
+ </div>
2632
+ ${parts.renderScript}
2633
+ </body>
2634
+ </html>`;
2635
+ }
2636
+ /**
2637
+ * Get cache statistics.
2638
+ */
2639
+ getCacheStats() {
2640
+ return this.cache.getStats();
2641
+ }
2642
+ /**
2643
+ * Clear the cache.
2644
+ */
2645
+ clearCache() {
2646
+ this.cache.clear();
2647
+ }
2648
+ /**
2649
+ * Clean up expired cache entries.
2650
+ */
2651
+ cleanupCache() {
2652
+ return this.cache.cleanup();
2653
+ }
2654
+ /**
2655
+ * Transform source code using esbuild/SWC.
2656
+ */
2657
+ async transform(source, sourceType, options) {
2658
+ const transform = await loadEsbuild();
2659
+ if (!transform) {
2660
+ throw new Error("No bundler available. Install esbuild or @swc/core: npm install esbuild");
2661
+ }
2662
+ const loader = this.getLoader(sourceType);
2663
+ const esbuildOptions = {
2664
+ loader,
2665
+ minify: options.minify,
2666
+ sourcemap: options.sourceMaps,
2667
+ target: options.target,
2668
+ format: options.format === "cjs" ? "cjs" : options.format === "esm" ? "esm" : "iife",
2669
+ jsx: "automatic",
2670
+ jsxImportSource: options.jsx.importSource
2671
+ };
2672
+ try {
2673
+ const result = await transform(source, esbuildOptions);
2674
+ return {
2675
+ code: result.code,
2676
+ map: result.map
2677
+ };
2678
+ } catch (error) {
2679
+ throw new Error(`Transform failed: ${error instanceof Error ? error.message : String(error)}`);
2680
+ }
2681
+ }
2682
+ /**
2683
+ * Get esbuild loader for source type.
2684
+ */
2685
+ getLoader(sourceType) {
2686
+ switch (sourceType) {
2687
+ case "jsx":
2688
+ return "jsx";
2689
+ case "tsx":
2690
+ return "tsx";
2691
+ case "mdx":
2692
+ return "tsx";
2693
+ // MDX compiles to JSX/TSX
2694
+ case "html":
2695
+ return "text";
2696
+ default:
2697
+ return "tsx";
2698
+ }
2699
+ }
2700
+ /**
2701
+ * Detect source type from content.
2702
+ */
2703
+ detectSourceType(source) {
2704
+ const hasTypeScript = /:\s*(string|number|boolean|any|unknown|void|never|object)\b/.test(source) || /interface\s+\w+/.test(source) || /type\s+\w+\s*=/.test(source) || /<\w+>/.test(source);
2705
+ const hasJSX = /<[A-Z][a-zA-Z]*/.test(source) || // Component tags
2706
+ /<[a-z]+\s/.test(source) || // HTML tags with attributes
2707
+ /<[a-z]+>/.test(source) || // Self-closing HTML tags
2708
+ /<\/[a-z]+>/.test(source);
2709
+ const hasMDX = /^#\s+/.test(source) || // Markdown heading
2710
+ /^-\s+/.test(source) || // Markdown list
2711
+ /\*\*\w+\*\*/.test(source) || // Bold
2712
+ /```\w*\n/.test(source);
2713
+ if (hasMDX && hasJSX) {
2714
+ return "mdx";
2715
+ }
2716
+ if (hasTypeScript && hasJSX) {
2717
+ return "tsx";
2718
+ }
2719
+ if (hasJSX) {
2720
+ return "jsx";
2721
+ }
2722
+ if (hasTypeScript) {
2723
+ return "tsx";
2724
+ }
2725
+ return "jsx";
2726
+ }
2727
+ /**
2728
+ * Merge bundle options with defaults.
2729
+ */
2730
+ mergeOptions(options) {
2731
+ return {
2732
+ sourceType: options.sourceType ?? DEFAULT_BUNDLE_OPTIONS.sourceType,
2733
+ format: options.format ?? DEFAULT_BUNDLE_OPTIONS.format,
2734
+ minify: options.minify ?? DEFAULT_BUNDLE_OPTIONS.minify,
2735
+ sourceMaps: options.sourceMaps ?? DEFAULT_BUNDLE_OPTIONS.sourceMaps,
2736
+ externals: options.externals ?? DEFAULT_BUNDLE_OPTIONS.externals,
2737
+ jsx: {
2738
+ ...DEFAULT_BUNDLE_OPTIONS.jsx,
2739
+ ...options.jsx
2740
+ },
2741
+ target: options.target ?? DEFAULT_BUNDLE_OPTIONS.target,
2742
+ globalName: options.globalName ?? DEFAULT_BUNDLE_OPTIONS.globalName,
2743
+ skipCache: options.skipCache ?? DEFAULT_BUNDLE_OPTIONS.skipCache
2744
+ };
2745
+ }
2746
+ /**
2747
+ * Build hydration script for client-side React.
2748
+ */
2749
+ buildHydrationScript(bundledCode, context) {
2750
+ const contextJson = context ? JSON.stringify(context) : "{}";
2751
+ return `
2752
+ (function() {
2753
+ var context = ${contextJson};
2754
+ var exports = {};
2755
+ var module = { exports: exports };
2756
+
2757
+ // Execute bundled code
2758
+ (function(exports, module) {
2759
+ ${bundledCode}
2760
+ })(exports, module);
2761
+
2762
+ // Get component
2763
+ var Component = module.exports.default || module.exports;
2764
+
2765
+ // Hydrate
2766
+ if (typeof ReactDOM !== 'undefined' && ReactDOM.hydrateRoot) {
2767
+ var container = document.getElementById('root') || document.body.firstElementChild;
2768
+ if (container) {
2769
+ ReactDOM.hydrateRoot(container, React.createElement(Component, context));
2770
+ }
2771
+ }
2772
+ })();
2773
+ `.trim();
2774
+ }
2775
+ // ============================================
2776
+ // Static HTML Helper Methods
2777
+ // ============================================
2778
+ /**
2779
+ * Merge static HTML options with defaults.
2780
+ */
2781
+ mergeStaticHTMLOptions(options) {
2782
+ return {
2783
+ sourceType: options.sourceType ?? DEFAULT_STATIC_HTML_OPTIONS.sourceType,
2784
+ targetPlatform: options.targetPlatform ?? DEFAULT_STATIC_HTML_OPTIONS.targetPlatform,
2785
+ minify: options.minify ?? DEFAULT_STATIC_HTML_OPTIONS.minify,
2786
+ skipCache: options.skipCache ?? DEFAULT_STATIC_HTML_OPTIONS.skipCache,
2787
+ rootId: sanitizeRootId(options.rootId ?? DEFAULT_STATIC_HTML_OPTIONS.rootId),
2788
+ widgetAccessible: options.widgetAccessible ?? DEFAULT_STATIC_HTML_OPTIONS.widgetAccessible,
2789
+ externals: {
2790
+ ...DEFAULT_STATIC_HTML_OPTIONS.externals,
2791
+ ...options.externals
2792
+ },
2793
+ // Universal mode options
2794
+ universal: options.universal ?? DEFAULT_STATIC_HTML_OPTIONS.universal,
2795
+ contentType: options.contentType ?? DEFAULT_STATIC_HTML_OPTIONS.contentType,
2796
+ includeMarkdown: options.includeMarkdown ?? DEFAULT_STATIC_HTML_OPTIONS.includeMarkdown,
2797
+ includeMdx: options.includeMdx ?? DEFAULT_STATIC_HTML_OPTIONS.includeMdx,
2798
+ // Pass-through options
2799
+ toolName: options.toolName,
2800
+ input: options.input,
2801
+ output: options.output,
2802
+ structuredContent: options.structuredContent,
2803
+ title: options.title,
2804
+ security: options.security,
2805
+ customCss: options.customCss,
2806
+ customComponents: options.customComponents
2807
+ };
2808
+ }
2809
+ /**
2810
+ * Build the <head> section for static HTML.
2811
+ */
2812
+ buildStaticHTMLHead(opts) {
2813
+ const parts = [];
2814
+ parts.push(`<meta charset="UTF-8">`);
2815
+ parts.push(`<meta name="viewport" content="width=device-width, initial-scale=1.0">`);
2816
+ for (const url of STATIC_HTML_CDN.fonts.preconnect) {
2817
+ parts.push(`<link rel="preconnect" href="${url}" crossorigin>`);
2818
+ }
2819
+ parts.push(`<link rel="stylesheet" href="${STATIC_HTML_CDN.fonts.inter}">`);
2820
+ const tailwindConfig = opts.externals.tailwind ?? "cdn";
2821
+ if (tailwindConfig === "cdn") {
2822
+ parts.push(`<link rel="stylesheet" href="${STATIC_HTML_CDN.tailwind}">`);
2823
+ } else if (tailwindConfig !== "inline" && tailwindConfig) {
2824
+ parts.push(`<link rel="stylesheet" href="${tailwindConfig}">`);
2825
+ }
2826
+ parts.push(`<style>
2827
+ body { margin: 0; font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
2828
+ .frontmcp-loading { display: flex; align-items: center; justify-content: center; min-height: 200px; }
2829
+ .frontmcp-spinner { width: 24px; height: 24px; border: 2px solid #e5e7eb; border-top-color: #3b82f6; border-radius: 50%; animation: spin 1s linear infinite; }
2830
+ @keyframes spin { to { transform: rotate(360deg); } }
2831
+ </style>`);
2832
+ if (opts.customCss) {
2833
+ parts.push(`<style>
2834
+ ${sanitizeCss(opts.customCss)}
2835
+ </style>`);
2836
+ }
2837
+ return parts.join("\n ");
2838
+ }
2839
+ /**
2840
+ * Build React runtime scripts for static HTML.
2841
+ */
2842
+ buildReactRuntimeScripts(externals, platform, cdnType) {
2843
+ const reactConfig = externals.react ?? "cdn";
2844
+ const reactDomConfig = externals.reactDom ?? "cdn";
2845
+ if (cdnType === "umd") {
2846
+ const reactUrl = reactConfig === "cdn" ? STATIC_HTML_CDN.umd.react : reactConfig;
2847
+ const reactDomUrl = reactDomConfig === "cdn" ? STATIC_HTML_CDN.umd.reactDom : reactDomConfig;
2848
+ return `
2849
+ <!-- React Runtime (UMD from cdnjs - Claude compatible) -->
2850
+ <script src="${reactUrl}"></script>
2851
+ <script src="${reactDomUrl}"></script>
2852
+ <script>
2853
+ // Webpack/esbuild polyfills for transpiled code (UMD globals)
2854
+ window.external_react_namespaceObject = window.React;
2855
+ window.jsx_runtime_namespaceObject = {
2856
+ jsx: function(type, props, key) {
2857
+ if (key !== undefined) props = Object.assign({}, props, { key: key });
2858
+ return React.createElement(type, props);
2859
+ },
2860
+ jsxs: function(type, props, key) {
2861
+ if (key !== undefined) props = Object.assign({}, props, { key: key });
2862
+ return React.createElement(type, props);
2863
+ },
2864
+ Fragment: React.Fragment
2865
+ };
2866
+ window.__reactReady = true;
2867
+ </script>`;
2868
+ } else {
2869
+ const reactUrl = reactConfig === "cdn" ? STATIC_HTML_CDN.esm.react : reactConfig;
2870
+ const reactDomUrl = reactDomConfig === "cdn" ? STATIC_HTML_CDN.esm.reactDom : reactDomConfig;
2871
+ return `
2872
+ <!-- React Runtime (ES modules from esm.sh) -->
2873
+ <script type="module">
2874
+ import React from '${reactUrl}';
2875
+ import { createRoot } from '${reactDomUrl}';
2876
+
2877
+ // Make React available globally
2878
+ window.React = React;
2879
+ window.ReactDOM = { createRoot };
2880
+
2881
+ // Webpack/esbuild polyfills for transpiled code
2882
+ window.external_react_namespaceObject = React;
2883
+ window.jsx_runtime_namespaceObject = {
2884
+ jsx: function(type, props, key) {
2885
+ if (key !== undefined) props = Object.assign({}, props, { key: key });
2886
+ return React.createElement(type, props);
2887
+ },
2888
+ jsxs: function(type, props, key) {
2889
+ if (key !== undefined) props = Object.assign({}, props, { key: key });
2890
+ return React.createElement(type, props);
2891
+ },
2892
+ Fragment: React.Fragment
2893
+ };
2894
+
2895
+ // Signal React is ready
2896
+ window.__reactReady = true;
2897
+ window.dispatchEvent(new CustomEvent('react:ready'));
2898
+ </script>`;
2899
+ }
2900
+ }
2901
+ /**
2902
+ * Build FrontMCP runtime (hooks and UI components).
2903
+ * Always inlined for reliability across platforms.
2904
+ */
2905
+ buildFrontMCPRuntime() {
2906
+ return `
2907
+ <!-- FrontMCP Runtime (always inline) -->
2908
+ <script>
2909
+ // Custom require() shim for browser - maps module names to globals
2910
+ // This allows esbuild-transpiled code to work in browsers
2911
+ window.__moduleCache = {};
2912
+ window.require = function(moduleName) {
2913
+ // Check cache first
2914
+ if (window.__moduleCache[moduleName]) {
2915
+ return window.__moduleCache[moduleName];
2916
+ }
2917
+
2918
+ // Map module names to browser globals
2919
+ var moduleMap = {
2920
+ 'react': function() { return window.React; },
2921
+ 'react-dom': function() { return window.ReactDOM; },
2922
+ 'react-dom/client': function() { return window.ReactDOM; },
2923
+ 'react/jsx-runtime': function() { return window.jsx_runtime_namespaceObject; },
2924
+ 'react/jsx-dev-runtime': function() { return window.jsx_runtime_namespaceObject; },
2925
+ '@frontmcp/ui': function() { return window.react_namespaceObject; },
2926
+ '@frontmcp/ui/react': function() { return window.react_namespaceObject; },
2927
+ };
2928
+
2929
+ var resolver = moduleMap[moduleName];
2930
+ if (resolver) {
2931
+ var mod = resolver();
2932
+ window.__moduleCache[moduleName] = mod;
2933
+ return mod;
2934
+ }
2935
+
2936
+ console.warn('[FrontMCP] Unknown module requested:', moduleName);
2937
+ return {};
2938
+ };
2939
+
2940
+ // Async require for dynamic imports (returns Promise)
2941
+ window.requireAsync = function(moduleName) {
2942
+ return new Promise(function(resolve, reject) {
2943
+ // If module is already loaded, resolve immediately
2944
+ var mod = window.require(moduleName);
2945
+ if (mod && Object.keys(mod).length > 0) {
2946
+ resolve(mod);
2947
+ return;
2948
+ }
2949
+
2950
+ // For now, we don't support dynamic CDN loading
2951
+ // All required modules should be pre-loaded
2952
+ console.warn('[FrontMCP] Async module not available:', moduleName);
2953
+ resolve({});
2954
+ });
2955
+ };
2956
+
2957
+ // FrontMCP Hook implementations
2958
+ window.__frontmcp = {
2959
+ // Context for MCP bridge
2960
+ context: {
2961
+ toolName: null,
2962
+ toolInput: null,
2963
+ toolOutput: null,
2964
+ structuredContent: null,
2965
+ callTool: null,
2966
+ },
2967
+
2968
+ // Set context from data injection
2969
+ setContext: function(ctx) {
2970
+ Object.assign(this.context, ctx);
2971
+ },
2972
+ };
2973
+
2974
+ // Hook: useToolOutput - returns the tool output data
2975
+ window.useToolOutput = function() {
2976
+ return window.__frontmcp.context.toolOutput;
2977
+ };
2978
+
2979
+ // Hook: useToolInput - returns the tool input arguments
2980
+ window.useToolInput = function() {
2981
+ return window.__frontmcp.context.toolInput;
2982
+ };
2983
+
2984
+ // Hook: useMcpBridgeContext - returns full bridge context
2985
+ window.useMcpBridgeContext = function() {
2986
+ return window.__frontmcp.context;
2987
+ };
2988
+
2989
+ // Hook: useCallTool - returns function to call other tools
2990
+ window.useCallTool = function() {
2991
+ return function(name, args) {
2992
+ if (window.__frontmcp.context.callTool) {
2993
+ return window.__frontmcp.context.callTool(name, args);
2994
+ }
2995
+ console.warn('[FrontMCP] callTool not available - widget may not have tool access');
2996
+ return Promise.resolve(null);
2997
+ };
2998
+ };
2999
+
3000
+ // UI Components (simplified inline versions)
3001
+ window.Card = function(props) {
3002
+ var children = props.children;
3003
+ var title = props.title;
3004
+ var className = props.className || '';
3005
+ return React.createElement('div', {
3006
+ className: 'bg-white rounded-lg shadow border border-gray-200 overflow-hidden ' + className
3007
+ }, [
3008
+ title && React.createElement('div', {
3009
+ key: 'header',
3010
+ className: 'px-4 py-3 border-b border-gray-200 bg-gray-50'
3011
+ }, React.createElement('h3', { className: 'text-sm font-medium text-gray-900' }, title)),
3012
+ React.createElement('div', { key: 'body', className: 'p-4' }, children)
3013
+ ]);
3014
+ };
3015
+
3016
+ window.Badge = function(props) {
3017
+ var children = props.children;
3018
+ var variant = props.variant || 'default';
3019
+ var variantClasses = {
3020
+ default: 'bg-gray-100 text-gray-800',
3021
+ success: 'bg-green-100 text-green-800',
3022
+ warning: 'bg-yellow-100 text-yellow-800',
3023
+ error: 'bg-red-100 text-red-800',
3024
+ info: 'bg-blue-100 text-blue-800',
3025
+ };
3026
+ return React.createElement('span', {
3027
+ className: 'inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ' + (variantClasses[variant] || variantClasses.default)
3028
+ }, children);
3029
+ };
3030
+
3031
+ window.Button = function(props) {
3032
+ var children = props.children;
3033
+ var variant = props.variant || 'primary';
3034
+ var onClick = props.onClick;
3035
+ var disabled = props.disabled;
3036
+ var variantClasses = {
3037
+ primary: 'bg-blue-600 text-white hover:bg-blue-700',
3038
+ secondary: 'bg-gray-100 text-gray-900 hover:bg-gray-200',
3039
+ outline: 'border border-gray-300 text-gray-700 hover:bg-gray-50',
3040
+ danger: 'bg-red-600 text-white hover:bg-red-700',
3041
+ };
3042
+ return React.createElement('button', {
3043
+ className: 'px-4 py-2 rounded-md text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 ' +
3044
+ (disabled ? 'opacity-50 cursor-not-allowed ' : '') +
3045
+ (variantClasses[variant] || variantClasses.primary),
3046
+ onClick: onClick,
3047
+ disabled: disabled,
3048
+ }, children);
3049
+ };
3050
+
3051
+ // Make hooks available on react_namespaceObject for bundled imports
3052
+ window.react_namespaceObject = Object.assign({}, window.React || {}, {
3053
+ useToolOutput: window.useToolOutput,
3054
+ useToolInput: window.useToolInput,
3055
+ useMcpBridgeContext: window.useMcpBridgeContext,
3056
+ useCallTool: window.useCallTool,
3057
+ Card: window.Card,
3058
+ Badge: window.Badge,
3059
+ Button: window.Button,
3060
+ });
3061
+ </script>`;
3062
+ }
3063
+ /**
3064
+ * Build data injection script for tool input/output.
3065
+ */
3066
+ buildDataInjectionScript(toolName, input, output, structuredContent) {
3067
+ const safeJson = (value) => {
3068
+ try {
3069
+ return JSON.stringify(value);
3070
+ } catch {
3071
+ return "null";
3072
+ }
3073
+ };
3074
+ return `
3075
+ <!-- Tool Data Injection -->
3076
+ <script>
3077
+ window.__mcpToolName = ${safeJson(toolName)};
3078
+ window.__mcpToolInput = ${safeJson(input ?? null)};
3079
+ window.__mcpToolOutput = ${safeJson(output ?? null)};
3080
+ window.__mcpStructuredContent = ${safeJson(structuredContent ?? null)};
3081
+
3082
+ // Initialize FrontMCP context
3083
+ window.__frontmcp.setContext({
3084
+ toolName: window.__mcpToolName,
3085
+ toolInput: window.__mcpToolInput,
3086
+ toolOutput: window.__mcpToolOutput,
3087
+ structuredContent: window.__mcpStructuredContent,
3088
+ });
3089
+ </script>`;
3090
+ }
3091
+ /**
3092
+ * Build component render script.
3093
+ * Wraps CommonJS code with module/exports shim to capture the component.
3094
+ */
3095
+ buildComponentRenderScript(componentCode, rootId, cdnType) {
3096
+ const wrappedCode = `
3097
+ // CommonJS module shim
3098
+ var module = { exports: {} };
3099
+ var exports = module.exports;
3100
+
3101
+ // Execute transpiled component code (CommonJS format)
3102
+ ${componentCode}
3103
+
3104
+ // Capture the component export
3105
+ window.__frontmcp_component = module.exports;
3106
+ `;
3107
+ if (cdnType === "umd") {
3108
+ return `
3109
+ <!-- Component Render Script (UMD - synchronous) -->
3110
+ <script>
3111
+ (function() {
3112
+ ${wrappedCode}
3113
+
3114
+ // Get the component
3115
+ var Component = window.__frontmcp_component.default || window.__frontmcp_component;
3116
+
3117
+ // Render the component
3118
+ var container = document.getElementById('${rootId}');
3119
+ if (container && window.ReactDOM && window.ReactDOM.createRoot) {
3120
+ var root = window.ReactDOM.createRoot(container);
3121
+ root.render(React.createElement(Component, {
3122
+ output: window.__mcpToolOutput,
3123
+ input: window.__mcpToolInput,
3124
+ }));
3125
+ } else if (container && window.ReactDOM && window.ReactDOM.render) {
3126
+ // Fallback for React 17
3127
+ window.ReactDOM.render(
3128
+ React.createElement(Component, {
3129
+ output: window.__mcpToolOutput,
3130
+ input: window.__mcpToolInput,
3131
+ }),
3132
+ container
3133
+ );
3134
+ }
3135
+ })();
3136
+ </script>`;
3137
+ } else {
3138
+ return `
3139
+ <!-- Component Render Script (ESM - waits for React) -->
3140
+ <script type="module">
3141
+ function renderComponent() {
3142
+ ${wrappedCode}
3143
+
3144
+ // Get the component
3145
+ var Component = window.__frontmcp_component.default || window.__frontmcp_component;
3146
+
3147
+ // Render the component
3148
+ var container = document.getElementById('${rootId}');
3149
+ if (container && window.ReactDOM && window.ReactDOM.createRoot) {
3150
+ var root = window.ReactDOM.createRoot(container);
3151
+ root.render(React.createElement(Component, {
3152
+ output: window.__mcpToolOutput,
3153
+ input: window.__mcpToolInput,
3154
+ }));
3155
+ }
3156
+ }
3157
+
3158
+ // Wait for React to be ready
3159
+ if (window.__reactReady) {
3160
+ renderComponent();
3161
+ } else {
3162
+ window.addEventListener('react:ready', renderComponent);
3163
+ }
3164
+ </script>`;
3165
+ }
3166
+ }
3167
+ /**
3168
+ * Assemble the complete static HTML document.
3169
+ */
3170
+ assembleStaticHTML(parts) {
3171
+ return `<!DOCTYPE html>
3172
+ <html lang="en">
3173
+ <head>
3174
+ <title>${escapeHtml(parts.title)}</title>
3175
+ ${parts.head}
3176
+ ${parts.reactRuntime}
3177
+ ${parts.frontmcpRuntime}
3178
+ ${parts.dataScript}
3179
+ </head>
3180
+ <body>
3181
+ <div id="${parts.rootId}" class="frontmcp-loading">
3182
+ <div class="frontmcp-spinner"></div>
3183
+ </div>
3184
+ ${parts.componentScript}
3185
+ </body>
3186
+ </html>`;
3187
+ }
3188
+ };
3189
+ function createBundler(options) {
3190
+ return new InMemoryBundler(options);
3191
+ }
3192
+
3193
+ // libs/ui/src/bundler/file-cache/storage/index.ts
3194
+ init_interface();
3195
+ init_filesystem();
3196
+ init_redis();
3197
+
3198
+ // libs/ui/src/bundler/file-cache/hash-calculator.ts
3199
+ import { createHash as createHash2 } from "crypto";
3200
+ import { readFile as readFile2 } from "fs/promises";
3201
+ import { existsSync as existsSync2 } from "fs";
3202
+ import { join as join2, dirname as dirname2, resolve } from "path";
3203
+ function sha256(content) {
3204
+ return createHash2("sha256").update(content, "utf8").digest("hex");
3205
+ }
3206
+ function sha256Buffer(buffer) {
3207
+ return createHash2("sha256").update(buffer).digest("hex");
3208
+ }
3209
+ async function hashFile(filePath) {
3210
+ try {
3211
+ const content = await readFile2(filePath);
3212
+ return sha256Buffer(content);
3213
+ } catch {
3214
+ return void 0;
3215
+ }
3216
+ }
3217
+ async function hashFiles(filePaths) {
3218
+ const hashes = [];
3219
+ for (const filePath of filePaths.sort()) {
3220
+ const hash = await hashFile(filePath);
3221
+ if (hash) {
3222
+ hashes.push(`${filePath}:${hash}`);
3223
+ }
3224
+ }
3225
+ return sha256(hashes.join("\n"));
3226
+ }
3227
+ async function calculateComponentHash(options) {
3228
+ const {
3229
+ entryPath,
3230
+ baseDir = dirname2(entryPath),
3231
+ externals = [],
3232
+ dependencies = {},
3233
+ bundleOptions = {},
3234
+ maxDepth = 10
3235
+ } = options;
3236
+ const absoluteEntryPath = resolve(entryPath);
3237
+ const files = /* @__PURE__ */ new Set();
3238
+ const fileHashes = {};
3239
+ await collectLocalDependencies(absoluteEntryPath, baseDir, files, maxDepth, 0);
3240
+ for (const file of files) {
3241
+ const hash = await hashFile(file);
3242
+ if (hash) {
3243
+ fileHashes[file] = hash;
3244
+ }
3245
+ }
3246
+ const sortedFiles = Array.from(files).sort();
3247
+ const fileHashContent = sortedFiles.map((f) => `${f}:${fileHashes[f] || "missing"}`).join("\n");
3248
+ const filesHash = sha256(fileHashContent);
3249
+ const optionsHash = sha256(JSON.stringify(sortedObject(bundleOptions)));
3250
+ const dependenciesHash = sha256(JSON.stringify(sortedObject(dependencies)));
3251
+ const combinedHash = sha256([filesHash, optionsHash, dependenciesHash].join(":"));
3252
+ return {
3253
+ hash: combinedHash,
3254
+ entryHash: fileHashes[absoluteEntryPath] || "",
3255
+ files: sortedFiles,
3256
+ fileHashes,
3257
+ optionsHash,
3258
+ dependenciesHash
3259
+ };
3260
+ }
3261
+ async function calculateQuickHash(entryPath, bundleOptions) {
3262
+ const entryHash = await hashFile(entryPath);
3263
+ const optionsHash = bundleOptions ? sha256(JSON.stringify(sortedObject(bundleOptions))) : "";
3264
+ return sha256(`${entryHash || "missing"}:${optionsHash}`);
3265
+ }
3266
+ async function collectLocalDependencies(filePath, baseDir, collected, maxDepth, currentDepth) {
3267
+ if (currentDepth >= maxDepth) return;
3268
+ if (collected.has(filePath)) return;
3269
+ if (!existsSync2(filePath)) return;
3270
+ collected.add(filePath);
3271
+ try {
3272
+ const content = await readFile2(filePath, "utf8");
3273
+ const imports = extractImportPaths(content);
3274
+ for (const importPath of imports) {
3275
+ if (!importPath.startsWith(".") && !importPath.startsWith("/")) {
3276
+ continue;
3277
+ }
3278
+ const resolvedPath = resolveImportPath(importPath, dirname2(filePath));
3279
+ if (resolvedPath && existsSync2(resolvedPath)) {
3280
+ await collectLocalDependencies(resolvedPath, baseDir, collected, maxDepth, currentDepth + 1);
3281
+ }
3282
+ }
3283
+ } catch {
3284
+ }
3285
+ }
3286
+ function extractImportPaths(source) {
3287
+ const paths = [];
3288
+ const importRegex = /import\s+(?:[^'"]+\s+from\s+)?['"]([^'"]+)['"]/g;
3289
+ let match;
3290
+ while ((match = importRegex.exec(source)) !== null) {
3291
+ paths.push(match[1]);
3292
+ }
3293
+ const exportRegex = /export\s+(?:\*|{[^}]+})\s+from\s+['"]([^'"]+)['"]/g;
3294
+ while ((match = exportRegex.exec(source)) !== null) {
3295
+ paths.push(match[1]);
3296
+ }
3297
+ const requireRegex = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
3298
+ while ((match = requireRegex.exec(source)) !== null) {
3299
+ paths.push(match[1]);
3300
+ }
3301
+ const dynamicRegex = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
3302
+ while ((match = dynamicRegex.exec(source)) !== null) {
3303
+ paths.push(match[1]);
3304
+ }
3305
+ return [...new Set(paths)];
3306
+ }
3307
+ function resolveImportPath(importPath, fromDir) {
3308
+ const extensions = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
3309
+ for (const ext of extensions) {
3310
+ const fullPath = join2(fromDir, importPath + ext);
3311
+ if (existsSync2(fullPath)) {
3312
+ return fullPath;
3313
+ }
3314
+ }
3315
+ for (const ext of extensions) {
3316
+ const indexPath = join2(fromDir, importPath, `index${ext}`);
3317
+ if (existsSync2(indexPath)) {
3318
+ return indexPath;
3319
+ }
3320
+ }
3321
+ return void 0;
3322
+ }
3323
+ function sortedObject(obj) {
3324
+ const sorted = {};
3325
+ const keys = Object.keys(obj).sort();
3326
+ for (const key of keys) {
3327
+ const value = obj[key];
3328
+ if (value && typeof value === "object" && !Array.isArray(value)) {
3329
+ sorted[key] = sortedObject(value);
3330
+ } else {
3331
+ sorted[key] = value;
3332
+ }
3333
+ }
3334
+ return sorted;
3335
+ }
3336
+ function generateBuildId() {
3337
+ const timestamp = Date.now().toString(36);
3338
+ const random = Math.random().toString(36).substring(2, 10);
3339
+ return `${timestamp}-${random}`;
3340
+ }
3341
+ function buildIdFromHash(hash) {
3342
+ return hash.substring(0, 12);
3343
+ }
3344
+
3345
+ // libs/ui/src/bundler/file-cache/component-builder.ts
3346
+ import { readFile as readFile3 } from "fs/promises";
3347
+ import { existsSync as existsSync3 } from "fs";
3348
+ import { resolve as resolve2, extname } from "path";
3349
+ import { randomUUID } from "crypto";
3350
+ import { DependencyResolver, createImportMap, generateDependencyHTML } from "@frontmcp/uipack/dependency";
3351
+ var ComponentBuilder = class {
3352
+ storage;
3353
+ esbuild = null;
3354
+ constructor(storage) {
3355
+ this.storage = storage;
3356
+ }
3357
+ /**
3358
+ * Build a component from a file path.
3359
+ */
3360
+ async build(options) {
3361
+ const startTime = performance.now();
3362
+ const {
3363
+ entryPath,
3364
+ toolName,
3365
+ externals = [],
3366
+ dependencies = {},
3367
+ bundleOptions = {},
3368
+ platform = "unknown",
3369
+ skipCache = false,
3370
+ ssr = false,
3371
+ ssrContext = {},
3372
+ executeCode: executeCode3
3373
+ } = options;
3374
+ const absoluteEntryPath = resolve2(entryPath);
3375
+ if (!existsSync3(absoluteEntryPath)) {
3376
+ throw new Error(`Entry file not found: ${absoluteEntryPath}`);
3377
+ }
3378
+ const hashResult = await calculateComponentHash({
3379
+ entryPath: absoluteEntryPath,
3380
+ externals,
3381
+ dependencies,
3382
+ bundleOptions
3383
+ });
3384
+ if (!skipCache) {
3385
+ const cached = await this.storage.get(hashResult.hash);
3386
+ if (cached) {
3387
+ return {
3388
+ manifest: cached,
3389
+ cached: true,
3390
+ buildTimeMs: performance.now() - startTime
3391
+ };
3392
+ }
3393
+ }
3394
+ const source = await readFile3(absoluteEntryPath, "utf8");
3395
+ const resolver = new DependencyResolver({ platform });
3396
+ const resolvedDeps = [];
3397
+ for (const pkg of externals) {
3398
+ try {
3399
+ const override = dependencies[pkg];
3400
+ const resolved = resolver.resolve(pkg, override);
3401
+ if (resolved) {
3402
+ resolvedDeps.push(resolved);
3403
+ }
3404
+ } catch (error) {
3405
+ console.warn(`Failed to resolve external "${pkg}": ${error}`);
3406
+ }
3407
+ }
3408
+ const allExternals = new Set(externals);
3409
+ for (const dep of resolvedDeps) {
3410
+ const entry = resolver.getRegistry()[dep.packageName];
3411
+ if (entry?.providers) {
3412
+ const providerConfig = Object.values(entry.providers)[0];
3413
+ if (providerConfig?.peerDependencies) {
3414
+ for (const peer of providerConfig.peerDependencies) {
3415
+ if (!allExternals.has(peer)) {
3416
+ allExternals.add(peer);
3417
+ try {
3418
+ const peerOverride = dependencies[peer];
3419
+ const resolved = resolver.resolve(peer, peerOverride);
3420
+ if (resolved) {
3421
+ resolvedDeps.push(resolved);
3422
+ }
3423
+ } catch {
3424
+ }
3425
+ }
3426
+ }
3427
+ }
3428
+ }
3429
+ }
3430
+ const importMap = createImportMap(resolvedDeps);
3431
+ const bundleResult = await this.bundleComponent({
3432
+ source,
3433
+ entryPath: absoluteEntryPath,
3434
+ externals: Array.from(allExternals),
3435
+ bundleOptions
3436
+ });
3437
+ let ssrHtml;
3438
+ if (ssr) {
3439
+ ssrHtml = await this.renderSSR(bundleResult.code, ssrContext, resolvedDeps, executeCode3);
3440
+ }
3441
+ const manifest = {
3442
+ version: "1.0",
3443
+ buildId: randomUUID(),
3444
+ toolName,
3445
+ entryPath: absoluteEntryPath,
3446
+ contentHash: hashResult.hash,
3447
+ dependencies: resolvedDeps,
3448
+ outputs: {
3449
+ code: bundleResult.code,
3450
+ sourceMap: bundleResult.map,
3451
+ ssrHtml
3452
+ },
3453
+ importMap,
3454
+ metadata: {
3455
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
3456
+ buildTimeMs: performance.now() - startTime,
3457
+ totalSize: Buffer.byteLength(bundleResult.code, "utf8"),
3458
+ bundlerVersion: bundleResult.bundlerVersion
3459
+ }
3460
+ };
3461
+ await this.storage.set(hashResult.hash, manifest);
3462
+ return {
3463
+ manifest,
3464
+ cached: false,
3465
+ buildTimeMs: performance.now() - startTime
3466
+ };
3467
+ }
3468
+ /**
3469
+ * Build multiple components.
3470
+ */
3471
+ async buildMany(options) {
3472
+ return Promise.all(options.map((opt) => this.build(opt)));
3473
+ }
3474
+ /**
3475
+ * Check if a component needs rebuilding.
3476
+ */
3477
+ async needsRebuild(options) {
3478
+ const absoluteEntryPath = resolve2(options.entryPath);
3479
+ const hashResult = await calculateComponentHash({
3480
+ entryPath: absoluteEntryPath,
3481
+ externals: options.externals,
3482
+ dependencies: options.dependencies,
3483
+ bundleOptions: options.bundleOptions
3484
+ });
3485
+ const cached = await this.storage.has(hashResult.hash);
3486
+ return !cached;
3487
+ }
3488
+ /**
3489
+ * Get a cached build if it exists.
3490
+ */
3491
+ async getCached(options) {
3492
+ const absoluteEntryPath = resolve2(options.entryPath);
3493
+ const hashResult = await calculateComponentHash({
3494
+ entryPath: absoluteEntryPath,
3495
+ externals: options.externals,
3496
+ dependencies: options.dependencies,
3497
+ bundleOptions: options.bundleOptions
3498
+ });
3499
+ return this.storage.get(hashResult.hash);
3500
+ }
3501
+ /**
3502
+ * Invalidate a cached build.
3503
+ */
3504
+ async invalidate(contentHash) {
3505
+ return this.storage.delete(contentHash);
3506
+ }
3507
+ /**
3508
+ * Generate complete HTML for a built component.
3509
+ */
3510
+ generateHTML(manifest, minify = false) {
3511
+ const parts = [];
3512
+ const dependencyHtml = generateDependencyHTML(manifest.dependencies, { minify });
3513
+ parts.push(dependencyHtml);
3514
+ parts.push(`<script type="module">${manifest.outputs.code}</script>`);
3515
+ return parts.join(minify ? "" : "\n");
3516
+ }
3517
+ /**
3518
+ * Bundle a component using esbuild.
3519
+ */
3520
+ async bundleComponent(options) {
3521
+ const { source, entryPath, externals, bundleOptions } = options;
3522
+ if (!this.esbuild) {
3523
+ try {
3524
+ this.esbuild = await import("esbuild");
3525
+ } catch {
3526
+ throw new Error("esbuild is required for component building. Install with: npm install esbuild");
3527
+ }
3528
+ }
3529
+ const ext = extname(entryPath).toLowerCase();
3530
+ const loader = ext === ".tsx" ? "tsx" : ext === ".ts" ? "ts" : ext === ".jsx" ? "jsx" : "js";
3531
+ try {
3532
+ const result = await this.esbuild.transform(source, {
3533
+ loader,
3534
+ format: "esm",
3535
+ minify: bundleOptions.minify ?? process.env["NODE_ENV"] === "production",
3536
+ sourcemap: bundleOptions.sourceMaps ? "inline" : false,
3537
+ target: bundleOptions.target ?? "es2020",
3538
+ treeShaking: bundleOptions.treeShake ?? true,
3539
+ jsx: "automatic",
3540
+ jsxImportSource: bundleOptions.jsxImportSource ?? "react",
3541
+ // Mark externals for later import map resolution
3542
+ banner: externals.length > 0 ? `/* externals: ${externals.join(", ")} */` : void 0
3543
+ });
3544
+ return {
3545
+ code: result.code,
3546
+ map: result.map || void 0,
3547
+ bundlerVersion: this.esbuild.version
3548
+ };
3549
+ } catch (error) {
3550
+ throw new Error(`Bundle failed for ${entryPath}: ${error}`);
3551
+ }
3552
+ }
3553
+ /**
3554
+ * Perform server-side rendering.
3555
+ */
3556
+ async renderSSR(code, context, dependencies, executeCode3) {
3557
+ const hasReact = dependencies.some((d) => d.packageName === "react");
3558
+ if (!hasReact) {
3559
+ console.warn("SSR requires React as an external dependency");
3560
+ return void 0;
3561
+ }
3562
+ try {
3563
+ const React = await import("react");
3564
+ const ReactDOMServer = await import("react-dom/server");
3565
+ const exports = {};
3566
+ const module = { exports };
3567
+ if (executeCode3) {
3568
+ executeCode3(code, exports, module, React);
3569
+ } else {
3570
+ const fn = new Function("exports", "module", "React", code);
3571
+ fn(exports, module, React);
3572
+ }
3573
+ const Component = module.exports.default || module.exports;
3574
+ if (typeof Component !== "function") {
3575
+ console.warn("SSR: No default component export found");
3576
+ return void 0;
3577
+ }
3578
+ const element = React.createElement(Component, context);
3579
+ return ReactDOMServer.renderToString(element);
3580
+ } catch (error) {
3581
+ console.warn(`SSR failed: ${error}`);
3582
+ return void 0;
3583
+ }
3584
+ }
3585
+ };
3586
+ async function createFilesystemBuilder(cacheDir = ".frontmcp-cache/builds") {
3587
+ const { FilesystemStorage: FilesystemStorage2 } = await Promise.resolve().then(() => (init_filesystem(), filesystem_exports));
3588
+ const storage = new FilesystemStorage2({ cacheDir });
3589
+ await storage.initialize();
3590
+ return new ComponentBuilder(storage);
3591
+ }
3592
+ async function createRedisBuilder(redisClient, keyPrefix = "frontmcp:ui:build:") {
3593
+ const { RedisStorage: RedisStorage2 } = await Promise.resolve().then(() => (init_redis(), redis_exports));
3594
+ const storage = new RedisStorage2({
3595
+ client: redisClient,
3596
+ keyPrefix
3597
+ });
3598
+ await storage.initialize();
3599
+ return new ComponentBuilder(storage);
3600
+ }
3601
+ export {
3602
+ BundlerCache,
3603
+ ComponentBuilder,
3604
+ DEFAULT_BUNDLER_OPTIONS,
3605
+ DEFAULT_BUNDLE_OPTIONS,
3606
+ DEFAULT_SECURITY_POLICY,
3607
+ DEFAULT_STATIC_HTML_OPTIONS,
3608
+ DEFAULT_STORAGE_OPTIONS,
3609
+ ExecutionError,
3610
+ FilesystemStorage,
3611
+ InMemoryBundler,
3612
+ RedisStorage,
3613
+ STATIC_HTML_CDN,
3614
+ SecurityError,
3615
+ buildIdFromHash,
3616
+ calculateComponentHash,
3617
+ calculateManifestSize,
3618
+ calculateQuickHash,
3619
+ createBundler,
3620
+ createCacheKey,
3621
+ createFilesystemBuilder,
3622
+ createFilesystemStorage,
3623
+ createRedisBuilder,
3624
+ createRedisStorage,
3625
+ executeCode,
3626
+ executeDefault,
3627
+ generateBuildId,
3628
+ getCdnTypeForPlatform,
3629
+ hashContent,
3630
+ hashFile,
3631
+ hashFiles,
3632
+ isExecutionError,
3633
+ mergePolicy,
3634
+ sha256,
3635
+ sha256Buffer,
3636
+ throwOnViolations,
3637
+ validateImports,
3638
+ validateSize,
3639
+ validateSource
3640
+ };