@frontmcp/uipack 1.10.8 → 1.10.9-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,541 +1,4 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // libs/uipack/src/component/index.ts
21
- var component_exports = {};
22
- __export(component_exports, {
23
- FRONTMCP_META_KEY: () => FRONTMCP_META_KEY,
24
- bundleFileSource: () => bundleFileSource,
25
- extractDefaultExportName: () => extractDefaultExportName,
26
- generateMountScript: () => generateMountScript,
27
- isFileSource: () => isFileSource,
28
- isFunctionSource: () => isFunctionSource,
29
- isImportSource: () => isImportSource,
30
- isNpmSource: () => isNpmSource,
31
- renderComponent: () => renderComponent,
32
- resolveUISource: () => resolveUISource,
33
- transpileReactSource: () => transpileReactSource
34
- });
35
- module.exports = __toCommonJS(component_exports);
36
-
37
- // libs/uipack/src/component/types.ts
38
- function isNpmSource(source) {
39
- return typeof source === "object" && source !== null && "npm" in source;
40
- }
41
- function isFileSource(source) {
42
- return typeof source === "object" && source !== null && "file" in source;
43
- }
44
- function isImportSource(source) {
45
- return typeof source === "object" && source !== null && "import" in source;
46
- }
47
- function isFunctionSource(source) {
48
- return typeof source === "function";
49
- }
50
- var FRONTMCP_META_KEY = "__frontmcp_meta";
51
-
52
- // libs/uipack/src/resolver/cdn-registry.ts
53
- var DEFAULT_CDN_REGISTRY = {
54
- react: {
55
- packageName: "react",
56
- defaultVersion: "19.2.4",
57
- providers: {
58
- cloudflare: {
59
- url: "https://cdnjs.cloudflare.com/ajax/libs/react/19.2.4/umd/react.production.min.js",
60
- global: "React",
61
- crossorigin: "anonymous"
62
- },
63
- jsdelivr: {
64
- url: "https://cdn.jsdelivr.net/npm/react@19.2.4/umd/react.production.min.js",
65
- global: "React",
66
- crossorigin: "anonymous"
67
- },
68
- unpkg: {
69
- url: "https://unpkg.com/react@19.2.4/umd/react.production.min.js",
70
- global: "React",
71
- crossorigin: "anonymous"
72
- },
73
- "esm.sh": {
74
- url: "https://esm.sh/react@19.2.4",
75
- esm: true,
76
- crossorigin: "anonymous"
77
- }
78
- },
79
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
80
- metadata: {
81
- description: "A JavaScript library for building user interfaces",
82
- homepage: "https://react.dev",
83
- license: "MIT"
84
- }
85
- },
86
- "react-dom": {
87
- packageName: "react-dom",
88
- defaultVersion: "19.2.4",
89
- providers: {
90
- cloudflare: {
91
- url: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.4/umd/react-dom.production.min.js",
92
- global: "ReactDOM",
93
- crossorigin: "anonymous",
94
- peerDependencies: ["react"]
95
- },
96
- jsdelivr: {
97
- url: "https://cdn.jsdelivr.net/npm/react-dom@19.2.4/umd/react-dom.production.min.js",
98
- global: "ReactDOM",
99
- crossorigin: "anonymous",
100
- peerDependencies: ["react"]
101
- },
102
- unpkg: {
103
- url: "https://unpkg.com/react-dom@19.2.4/umd/react-dom.production.min.js",
104
- global: "ReactDOM",
105
- crossorigin: "anonymous",
106
- peerDependencies: ["react"]
107
- },
108
- "esm.sh": {
109
- url: "https://esm.sh/react-dom@19.2.4",
110
- esm: true,
111
- crossorigin: "anonymous",
112
- peerDependencies: ["react"]
113
- }
114
- },
115
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
116
- metadata: {
117
- description: "React package for working with the DOM",
118
- homepage: "https://react.dev",
119
- license: "MIT"
120
- }
121
- },
122
- "chart.js": {
123
- packageName: "chart.js",
124
- defaultVersion: "4.5.1",
125
- providers: {
126
- cloudflare: {
127
- url: "https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js",
128
- global: "Chart",
129
- crossorigin: "anonymous"
130
- },
131
- jsdelivr: {
132
- url: "https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js",
133
- global: "Chart",
134
- crossorigin: "anonymous"
135
- },
136
- unpkg: {
137
- url: "https://unpkg.com/chart.js@4.5.1/dist/chart.umd.min.js",
138
- global: "Chart",
139
- crossorigin: "anonymous"
140
- }
141
- },
142
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
143
- metadata: {
144
- description: "Simple yet flexible JavaScript charting library",
145
- homepage: "https://www.chartjs.org",
146
- license: "MIT"
147
- }
148
- },
149
- d3: {
150
- packageName: "d3",
151
- defaultVersion: "7.9.0",
152
- providers: {
153
- cloudflare: {
154
- url: "https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js",
155
- integrity: "sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==",
156
- global: "d3",
157
- crossorigin: "anonymous"
158
- },
159
- jsdelivr: {
160
- url: "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js",
161
- global: "d3",
162
- crossorigin: "anonymous"
163
- },
164
- unpkg: {
165
- url: "https://unpkg.com/d3@7.9.0/dist/d3.min.js",
166
- global: "d3",
167
- crossorigin: "anonymous"
168
- }
169
- },
170
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
171
- metadata: {
172
- description: "Data-Driven Documents",
173
- homepage: "https://d3js.org",
174
- license: "ISC"
175
- }
176
- },
177
- lodash: {
178
- packageName: "lodash",
179
- defaultVersion: "4.17.21",
180
- providers: {
181
- cloudflare: {
182
- url: "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",
183
- integrity: "sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==",
184
- global: "_",
185
- crossorigin: "anonymous"
186
- },
187
- jsdelivr: {
188
- url: "https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",
189
- global: "_",
190
- crossorigin: "anonymous"
191
- },
192
- unpkg: {
193
- url: "https://unpkg.com/lodash@4.17.21/lodash.min.js",
194
- global: "_",
195
- crossorigin: "anonymous"
196
- }
197
- },
198
- preferredProviders: ["esm.sh", "cloudflare", "jsdelivr", "unpkg"],
199
- metadata: {
200
- description: "A modern JavaScript utility library",
201
- homepage: "https://lodash.com",
202
- license: "MIT"
203
- }
204
- }
205
- };
206
- function lookupPackage(packageName, registry = DEFAULT_CDN_REGISTRY) {
207
- return registry[packageName];
208
- }
209
-
210
- // libs/uipack/src/resolver/import-parser.ts
211
- var IMPORT_PATTERNS = {
212
- named: /import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
213
- default: /import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
214
- namespace: /import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
215
- sideEffect: /import\s*['"]([^'"]+)['"]/g,
216
- dynamic: /(?:await\s+)?import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
217
- defaultAndNamed: /import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,
218
- defaultAndNamespace: /import\s+(\w+)\s*,\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,
219
- reExport: /export\s*\{[^}]+\}\s*from\s*['"]([^'"]+)['"]/g,
220
- reExportAll: /export\s*\*\s*from\s*['"]([^'"]+)['"]/g
221
- };
222
- function parseNamedImports(namedString) {
223
- return namedString.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((s) => {
224
- const asMatch = s.match(/^(\w+)\s+as\s+\w+$/);
225
- return asMatch ? asMatch[1] : s;
226
- });
227
- }
228
- function isRelativeImport(specifier) {
229
- return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/");
230
- }
231
- function isExternalImport(specifier) {
232
- return !isRelativeImport(specifier) && !specifier.startsWith("#");
233
- }
234
- function getPackageName(specifier) {
235
- if (specifier.startsWith("@")) {
236
- const parts = specifier.split("/");
237
- if (parts.length >= 2) {
238
- return `${parts[0]}/${parts[1]}`;
239
- }
240
- return specifier;
241
- }
242
- const firstSlash = specifier.indexOf("/");
243
- return firstSlash === -1 ? specifier : specifier.slice(0, firstSlash);
244
- }
245
- function getLineNumber(source, index) {
246
- let line = 1;
247
- for (let i = 0; i < index && i < source.length; i++) {
248
- if (source[i] === "\n") {
249
- line++;
250
- }
251
- }
252
- return line;
253
- }
254
- function getColumnNumber(source, index) {
255
- let column = 0;
256
- for (let i = index - 1; i >= 0 && source[i] !== "\n"; i--) {
257
- column++;
258
- }
259
- return column;
260
- }
261
- function parseImports(source) {
262
- const imports = [];
263
- const seenStatements = /* @__PURE__ */ new Set();
264
- const addImport = (imp) => {
265
- const key = `${imp.type}:${imp.specifier}:${imp.statement}`;
266
- if (!seenStatements.has(key)) {
267
- seenStatements.add(key);
268
- imports.push(imp);
269
- }
270
- };
271
- let match;
272
- const defaultAndNamedRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamed.source, "g");
273
- while ((match = defaultAndNamedRegex.exec(source)) !== null) {
274
- const [statement, defaultName, namedString, specifier] = match;
275
- addImport({
276
- statement,
277
- specifier,
278
- type: "default",
279
- defaultImport: defaultName,
280
- namedImports: parseNamedImports(namedString),
281
- line: getLineNumber(source, match.index),
282
- column: getColumnNumber(source, match.index)
283
- });
284
- }
285
- const defaultAndNamespaceRegex = new RegExp(IMPORT_PATTERNS.defaultAndNamespace.source, "g");
286
- while ((match = defaultAndNamespaceRegex.exec(source)) !== null) {
287
- const [statement, defaultName, namespaceName, specifier] = match;
288
- addImport({
289
- statement,
290
- specifier,
291
- type: "default",
292
- defaultImport: defaultName,
293
- namespaceImport: namespaceName,
294
- line: getLineNumber(source, match.index),
295
- column: getColumnNumber(source, match.index)
296
- });
297
- }
298
- const namedRegex = new RegExp(IMPORT_PATTERNS.named.source, "g");
299
- while ((match = namedRegex.exec(source)) !== null) {
300
- const [statement, namedString, specifier] = match;
301
- addImport({
302
- statement,
303
- specifier,
304
- type: "named",
305
- namedImports: parseNamedImports(namedString),
306
- line: getLineNumber(source, match.index),
307
- column: getColumnNumber(source, match.index)
308
- });
309
- }
310
- const defaultRegex = new RegExp(IMPORT_PATTERNS.default.source, "g");
311
- while ((match = defaultRegex.exec(source)) !== null) {
312
- const [statement, defaultName, specifier] = match;
313
- const afterMatch = source.slice(match.index + match[0].length - specifier.length - 2);
314
- if (afterMatch.startsWith(",")) continue;
315
- addImport({
316
- statement,
317
- specifier,
318
- type: "default",
319
- defaultImport: defaultName,
320
- line: getLineNumber(source, match.index),
321
- column: getColumnNumber(source, match.index)
322
- });
323
- }
324
- const namespaceRegex = new RegExp(IMPORT_PATTERNS.namespace.source, "g");
325
- while ((match = namespaceRegex.exec(source)) !== null) {
326
- const [statement, namespaceName, specifier] = match;
327
- addImport({
328
- statement,
329
- specifier,
330
- type: "namespace",
331
- namespaceImport: namespaceName,
332
- line: getLineNumber(source, match.index),
333
- column: getColumnNumber(source, match.index)
334
- });
335
- }
336
- const sideEffectRegex = new RegExp(IMPORT_PATTERNS.sideEffect.source, "g");
337
- while ((match = sideEffectRegex.exec(source)) !== null) {
338
- const [statement, specifier] = match;
339
- const beforeMatch = source.slice(Math.max(0, match.index - 50), match.index);
340
- if (beforeMatch.includes("from")) continue;
341
- addImport({
342
- statement,
343
- specifier,
344
- type: "side-effect",
345
- line: getLineNumber(source, match.index),
346
- column: getColumnNumber(source, match.index)
347
- });
348
- }
349
- const dynamicRegex = new RegExp(IMPORT_PATTERNS.dynamic.source, "g");
350
- while ((match = dynamicRegex.exec(source)) !== null) {
351
- const [statement, specifier] = match;
352
- addImport({
353
- statement,
354
- specifier,
355
- type: "dynamic",
356
- line: getLineNumber(source, match.index),
357
- column: getColumnNumber(source, match.index)
358
- });
359
- }
360
- const reExportRegex = new RegExp(IMPORT_PATTERNS.reExport.source, "g");
361
- while ((match = reExportRegex.exec(source)) !== null) {
362
- const [statement, specifier] = match;
363
- addImport({
364
- statement,
365
- specifier,
366
- type: "named",
367
- line: getLineNumber(source, match.index),
368
- column: getColumnNumber(source, match.index)
369
- });
370
- }
371
- const reExportAllRegex = new RegExp(IMPORT_PATTERNS.reExportAll.source, "g");
372
- while ((match = reExportAllRegex.exec(source)) !== null) {
373
- const [statement, specifier] = match;
374
- addImport({
375
- statement,
376
- specifier,
377
- type: "namespace",
378
- line: getLineNumber(source, match.index),
379
- column: getColumnNumber(source, match.index)
380
- });
381
- }
382
- const externalImports = imports.filter((imp) => isExternalImport(imp.specifier));
383
- const relativeImports = imports.filter((imp) => isRelativeImport(imp.specifier));
384
- const externalPackages = [...new Set(externalImports.map((imp) => getPackageName(imp.specifier)))];
385
- return {
386
- imports,
387
- externalImports,
388
- relativeImports,
389
- externalPackages
390
- };
391
- }
392
-
393
- // libs/uipack/src/resolver/esm-sh.resolver.ts
394
- var DEFAULT_FALLBACK_CDN = "https://esm.sh";
395
- function createEsmShResolver(options = {}) {
396
- const {
397
- fallbackCdnBase = DEFAULT_FALLBACK_CDN,
398
- registry = DEFAULT_CDN_REGISTRY,
399
- providerOrder = ["esm.sh", "cloudflare", "jsdelivr", "unpkg"]
400
- } = options;
401
- return {
402
- resolve(specifier, _context) {
403
- if (specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/")) {
404
- return null;
405
- }
406
- if (specifier.startsWith("node:") || specifier.startsWith("#")) {
407
- return null;
408
- }
409
- const pkgName = getPackageName(specifier);
410
- const entry = lookupPackage(pkgName, registry);
411
- if (entry) {
412
- for (const provider of providerOrder) {
413
- const config = entry.providers[provider];
414
- if (config?.url) {
415
- const subpath = specifier.slice(pkgName.length);
416
- if (subpath && config.url.includes("esm.sh/")) {
417
- return {
418
- value: config.url + subpath,
419
- type: "url",
420
- integrity: config.integrity
421
- };
422
- }
423
- if (subpath) {
424
- return {
425
- value: `${fallbackCdnBase}/${specifier}`,
426
- type: "url"
427
- };
428
- }
429
- if (config.global && !config.esm) {
430
- return {
431
- value: config.url,
432
- type: "url",
433
- integrity: config.integrity
434
- };
435
- }
436
- return {
437
- value: config.url,
438
- type: "url",
439
- integrity: config.integrity
440
- };
441
- }
442
- }
443
- }
444
- return {
445
- value: `${fallbackCdnBase}/${specifier}`,
446
- type: "url"
447
- };
448
- }
449
- };
450
- }
451
-
452
- // libs/uipack/src/utils/index.ts
453
- var SCRIPT_UNSAFE_CHARACTERS = /[<>&\u2028\u2029]/g;
454
- function toUnicodeEscape(character) {
455
- return `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
456
- }
457
- function safeJsonForScript(value) {
458
- if (value === void 0) {
459
- return "null";
460
- }
461
- try {
462
- const jsonString = JSON.stringify(value, (_key, val) => {
463
- if (typeof val === "bigint") {
464
- return val.toString();
465
- }
466
- return val;
467
- });
468
- if (jsonString === void 0) {
469
- return "null";
470
- }
471
- return jsonString.replace(SCRIPT_UNSAFE_CHARACTERS, toUnicodeEscape);
472
- } catch {
473
- return '{"error":"Value could not be serialized"}';
474
- }
475
- }
476
-
477
- // libs/uipack/src/component/ui-availability.ts
478
- function isFrontmcpUiResolvable(...candidatePaths) {
479
- try {
480
- const nodeFs = require("fs");
481
- const nodePath = require("path");
482
- const ORG = "@frontmcp";
483
- const PKG = "ui";
484
- for (const candidate of candidatePaths) {
485
- let dir = candidate;
486
- while (true) {
487
- const pkgJson = nodePath.join(dir, "node_modules", ORG, PKG, "package.json");
488
- if (nodeFs.existsSync(pkgJson)) return true;
489
- const parent = nodePath.dirname(dir);
490
- if (parent === dir) break;
491
- dir = parent;
492
- }
493
- }
494
- return false;
495
- } catch {
496
- return false;
497
- }
498
- }
499
-
500
- // libs/uipack/src/component/transpiler.ts
501
- function loadEsbuild(filename) {
502
- try {
503
- return require("esbuild");
504
- } catch (err) {
505
- if (!isMissingEsbuild(err)) throw err;
506
- const subject = filename ? `FileSource widget "${filename}"` : "A FileSource widget";
507
- throw new Error(
508
- `${subject} needs esbuild, which is not installed. @frontmcp/uipack loads esbuild on demand to bundle FileSource widgets (.tsx/.jsx) when the tool is called, so it must be installed where the server runs: \`npm install esbuild\` (in "dependencies", not "devDependencies"). Projects created with \`frontmcp create\` already get it through the \`frontmcp\` package.`,
509
- { cause: err }
510
- );
511
- }
512
- }
513
- function isMissingEsbuild(err) {
514
- if (!(err instanceof Error)) return false;
515
- return err.code === "MODULE_NOT_FOUND" && /Cannot find module ['"]esbuild['"]/.test(err.message);
516
- }
517
- function transpileReactSource(source, filename) {
518
- const esbuild = loadEsbuild(filename);
519
- const loader = filename?.endsWith(".tsx") ? "tsx" : "jsx";
520
- const result = esbuild.transformSync(source, {
521
- loader,
522
- jsx: "transform",
523
- jsxFactory: "React.createElement",
524
- jsxFragment: "React.Fragment",
525
- format: "esm",
526
- target: "es2020",
527
- define: { "process.env.NODE_ENV": '"production"' }
528
- });
529
- return result.code;
530
- }
531
- function bundleFileSource(source, filename, resolveDir, componentName, options = {}) {
532
- if (!isFrontmcpUiResolvable(resolveDir, process.cwd())) {
533
- throw new Error(
534
- `FileSource widget "${filename}" requires the @frontmcp/ui package, which provides the React bridge mount that's injected at bundle time. Install it (e.g. \`npm install @frontmcp/ui\` or \`yarn add @frontmcp/ui\`) and try again.`
535
- );
536
- }
537
- const esbuild = loadEsbuild(filename);
538
- const mountCode = `
1
+ "use strict";var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var component_exports={};__export(component_exports,{FRONTMCP_META_KEY:()=>FRONTMCP_META_KEY,bundleFileSource:()=>bundleFileSource,extractDefaultExportName:()=>extractDefaultExportName,generateMountScript:()=>generateMountScript,isFileSource:()=>isFileSource,isFunctionSource:()=>isFunctionSource,isImportSource:()=>isImportSource,isNpmSource:()=>isNpmSource,renderComponent:()=>renderComponent,resolveUISource:()=>resolveUISource,transpileReactSource:()=>transpileReactSource});module.exports=__toCommonJS(component_exports);function isNpmSource(source){return typeof source==="object"&&source!==null&&"npm"in source}function isFileSource(source){return typeof source==="object"&&source!==null&&"file"in source}function isImportSource(source){return typeof source==="object"&&source!==null&&"import"in source}function isFunctionSource(source){return typeof source==="function"}var FRONTMCP_META_KEY="__frontmcp_meta";var DEFAULT_CDN_REGISTRY={react:{packageName:"react",defaultVersion:"19.2.4",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/react/19.2.4/umd/react.production.min.js",global:"React",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/react@19.2.4/umd/react.production.min.js",global:"React",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/react@19.2.4/umd/react.production.min.js",global:"React",crossorigin:"anonymous"},"esm.sh":{url:"https://esm.sh/react@19.2.4",esm:true,crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"A JavaScript library for building user interfaces",homepage:"https://react.dev",license:"MIT"}},"react-dom":{packageName:"react-dom",defaultVersion:"19.2.4",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/react-dom/19.2.4/umd/react-dom.production.min.js",global:"ReactDOM",crossorigin:"anonymous",peerDependencies:["react"]},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/react-dom@19.2.4/umd/react-dom.production.min.js",global:"ReactDOM",crossorigin:"anonymous",peerDependencies:["react"]},unpkg:{url:"https://unpkg.com/react-dom@19.2.4/umd/react-dom.production.min.js",global:"ReactDOM",crossorigin:"anonymous",peerDependencies:["react"]},"esm.sh":{url:"https://esm.sh/react-dom@19.2.4",esm:true,crossorigin:"anonymous",peerDependencies:["react"]}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"React package for working with the DOM",homepage:"https://react.dev",license:"MIT"}},"chart.js":{packageName:"chart.js",defaultVersion:"4.5.1",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.1/chart.umd.min.js",global:"Chart",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/chart.js@4.5.1/dist/chart.umd.min.js",global:"Chart",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/chart.js@4.5.1/dist/chart.umd.min.js",global:"Chart",crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"Simple yet flexible JavaScript charting library",homepage:"https://www.chartjs.org",license:"MIT"}},d3:{packageName:"d3",defaultVersion:"7.9.0",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/d3/7.9.0/d3.min.js",integrity:"sha512-vc58qvvBdrDR4etbxMdlTt4GBQk1qjvyORR2nrsPsFPyrs+/u5c3+1Ct6upOgdZoIl7eq6k3a1UPDSNAQi/32A==",global:"d3",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js",global:"d3",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/d3@7.9.0/dist/d3.min.js",global:"d3",crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"Data-Driven Documents",homepage:"https://d3js.org",license:"ISC"}},lodash:{packageName:"lodash",defaultVersion:"4.17.21",providers:{cloudflare:{url:"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js",integrity:"sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==",global:"_",crossorigin:"anonymous"},jsdelivr:{url:"https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js",global:"_",crossorigin:"anonymous"},unpkg:{url:"https://unpkg.com/lodash@4.17.21/lodash.min.js",global:"_",crossorigin:"anonymous"}},preferredProviders:["esm.sh","cloudflare","jsdelivr","unpkg"],metadata:{description:"A modern JavaScript utility library",homepage:"https://lodash.com",license:"MIT"}}};function lookupPackage(packageName,registry=DEFAULT_CDN_REGISTRY){return registry[packageName]}var IMPORT_PATTERNS={named:/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,default:/import\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,namespace:/import\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,sideEffect:/import\s*['"]([^'"]+)['"]/g,dynamic:/(?:await\s+)?import\s*\(\s*['"]([^'"]+)['"]\s*\)/g,defaultAndNamed:/import\s+(\w+)\s*,\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g,defaultAndNamespace:/import\s+(\w+)\s*,\s*\*\s*as\s+(\w+)\s+from\s*['"]([^'"]+)['"]/g,reExport:/export\s*\{[^}]+\}\s*from\s*['"]([^'"]+)['"]/g,reExportAll:/export\s*\*\s*from\s*['"]([^'"]+)['"]/g};function parseNamedImports(namedString){return namedString.split(",").map(s=>s.trim()).filter(s=>s.length>0).map(s=>{const asMatch=s.match(/^(\w+)\s+as\s+\w+$/);return asMatch?asMatch[1]:s})}function isRelativeImport(specifier){return specifier.startsWith("./")||specifier.startsWith("../")||specifier.startsWith("/")}function isExternalImport(specifier){return!isRelativeImport(specifier)&&!specifier.startsWith("#")}function getPackageName(specifier){if(specifier.startsWith("@")){const parts=specifier.split("/");if(parts.length>=2){return`${parts[0]}/${parts[1]}`}return specifier}const firstSlash=specifier.indexOf("/");return firstSlash===-1?specifier:specifier.slice(0,firstSlash)}function getLineNumber(source,index){let line=1;for(let i=0;i<index&&i<source.length;i++){if(source[i]==="\n"){line++}}return line}function getColumnNumber(source,index){let column=0;for(let i=index-1;i>=0&&source[i]!=="\n";i--){column++}return column}function parseImports(source){const imports=[];const seenStatements=new Set;const addImport=imp=>{const key=`${imp.type}:${imp.specifier}:${imp.statement}`;if(!seenStatements.has(key)){seenStatements.add(key);imports.push(imp)}};let match;const defaultAndNamedRegex=new RegExp(IMPORT_PATTERNS.defaultAndNamed.source,"g");while((match=defaultAndNamedRegex.exec(source))!==null){const[statement,defaultName,namedString,specifier]=match;addImport({statement,specifier,type:"default",defaultImport:defaultName,namedImports:parseNamedImports(namedString),line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const defaultAndNamespaceRegex=new RegExp(IMPORT_PATTERNS.defaultAndNamespace.source,"g");while((match=defaultAndNamespaceRegex.exec(source))!==null){const[statement,defaultName,namespaceName,specifier]=match;addImport({statement,specifier,type:"default",defaultImport:defaultName,namespaceImport:namespaceName,line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const namedRegex=new RegExp(IMPORT_PATTERNS.named.source,"g");while((match=namedRegex.exec(source))!==null){const[statement,namedString,specifier]=match;addImport({statement,specifier,type:"named",namedImports:parseNamedImports(namedString),line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const defaultRegex=new RegExp(IMPORT_PATTERNS.default.source,"g");while((match=defaultRegex.exec(source))!==null){const[statement,defaultName,specifier]=match;const afterMatch=source.slice(match.index+match[0].length-specifier.length-2);if(afterMatch.startsWith(","))continue;addImport({statement,specifier,type:"default",defaultImport:defaultName,line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const namespaceRegex=new RegExp(IMPORT_PATTERNS.namespace.source,"g");while((match=namespaceRegex.exec(source))!==null){const[statement,namespaceName,specifier]=match;addImport({statement,specifier,type:"namespace",namespaceImport:namespaceName,line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const sideEffectRegex=new RegExp(IMPORT_PATTERNS.sideEffect.source,"g");while((match=sideEffectRegex.exec(source))!==null){const[statement,specifier]=match;const beforeMatch=source.slice(Math.max(0,match.index-50),match.index);if(beforeMatch.includes("from"))continue;addImport({statement,specifier,type:"side-effect",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const dynamicRegex=new RegExp(IMPORT_PATTERNS.dynamic.source,"g");while((match=dynamicRegex.exec(source))!==null){const[statement,specifier]=match;addImport({statement,specifier,type:"dynamic",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const reExportRegex=new RegExp(IMPORT_PATTERNS.reExport.source,"g");while((match=reExportRegex.exec(source))!==null){const[statement,specifier]=match;addImport({statement,specifier,type:"named",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const reExportAllRegex=new RegExp(IMPORT_PATTERNS.reExportAll.source,"g");while((match=reExportAllRegex.exec(source))!==null){const[statement,specifier]=match;addImport({statement,specifier,type:"namespace",line:getLineNumber(source,match.index),column:getColumnNumber(source,match.index)})}const externalImports=imports.filter(imp=>isExternalImport(imp.specifier));const relativeImports=imports.filter(imp=>isRelativeImport(imp.specifier));const externalPackages=[...new Set(externalImports.map(imp=>getPackageName(imp.specifier)))];return{imports,externalImports,relativeImports,externalPackages}}var DEFAULT_FALLBACK_CDN="https://esm.sh";function createEsmShResolver(options={}){const{fallbackCdnBase=DEFAULT_FALLBACK_CDN,registry=DEFAULT_CDN_REGISTRY,providerOrder=["esm.sh","cloudflare","jsdelivr","unpkg"]}=options;return{resolve(specifier,_context){if(specifier.startsWith("./")||specifier.startsWith("../")||specifier.startsWith("/")){return null}if(specifier.startsWith("node:")||specifier.startsWith("#")){return null}const pkgName=getPackageName(specifier);const entry=lookupPackage(pkgName,registry);if(entry){for(const provider of providerOrder){const config=entry.providers[provider];if(config?.url){const subpath=specifier.slice(pkgName.length);if(subpath&&config.url.includes("esm.sh/")){return{value:config.url+subpath,type:"url",integrity:config.integrity}}if(subpath){return{value:`${fallbackCdnBase}/${specifier}`,type:"url"}}if(config.global&&!config.esm){return{value:config.url,type:"url",integrity:config.integrity}}return{value:config.url,type:"url",integrity:config.integrity}}}}return{value:`${fallbackCdnBase}/${specifier}`,type:"url"}}}}var SCRIPT_UNSAFE_CHARACTERS=/[<>&\u2028\u2029]/g;function toUnicodeEscape(character){return`\\u${character.charCodeAt(0).toString(16).padStart(4,"0")}`}function safeJsonForScript(value){if(value===void 0){return"null"}try{const jsonString=JSON.stringify(value,(_key,val)=>{if(typeof val==="bigint"){return val.toString()}return val});if(jsonString===void 0){return"null"}return jsonString.replace(SCRIPT_UNSAFE_CHARACTERS,toUnicodeEscape)}catch{return'{"error":"Value could not be serialized"}'}}function isFrontmcpUiResolvable(...candidatePaths){try{const nodeFs=require("fs");const nodePath=require("path");const ORG="@frontmcp";const PKG="ui";for(const candidate of candidatePaths){let dir=candidate;while(true){const pkgJson=nodePath.join(dir,"node_modules",ORG,PKG,"package.json");if(nodeFs.existsSync(pkgJson))return true;const parent=nodePath.dirname(dir);if(parent===dir)break;dir=parent}}return false}catch{return false}}function loadEsbuild(filename){try{return require("esbuild")}catch(err){if(!isMissingEsbuild(err))throw err;const subject=filename?`FileSource widget "${filename}"`:"A FileSource widget";throw new Error(`${subject} needs esbuild, which is not installed. @frontmcp/uipack loads esbuild on demand to bundle FileSource widgets (.tsx/.jsx) when the tool is called, so it must be installed where the server runs: \`npm install esbuild\` (in "dependencies", not "devDependencies"). Projects created with \`frontmcp create\` already get it through the \`frontmcp\` package.`,{cause:err})}}function isMissingEsbuild(err){if(!(err instanceof Error))return false;return err.code==="MODULE_NOT_FOUND"&&/Cannot find module ['"]esbuild['"]/.test(err.message)}function transpileReactSource(source,filename){const esbuild=loadEsbuild(filename);const loader=filename?.endsWith(".tsx")?"tsx":"jsx";const result=esbuild.transformSync(source,{loader,jsx:"transform",jsxFactory:"React.createElement",jsxFragment:"React.Fragment",format:"esm",target:"es2020",define:{"process.env.NODE_ENV":'"production"'}});return result.code}function bundleFileSource(source,filename,resolveDir,componentName,options={}){if(!isFrontmcpUiResolvable(resolveDir,process.cwd())){throw new Error(`FileSource widget "${filename}" requires the @frontmcp/ui package, which provides the React bridge mount that's injected at bundle time. Install it (e.g. \`npm install @frontmcp/ui\` or \`yarn add @frontmcp/ui\`) and try again.`)}const esbuild=loadEsbuild(filename);const mountCode=`
539
2
  // --- Auto-generated mount ---
540
3
  import { createElement as __h } from 'react';
541
4
  import { createRoot } from 'react-dom/client';
@@ -577,364 +40,19 @@ if (__root) {
577
40
  if (d) __render(d.structuredContent !== undefined ? d.structuredContent : d.content !== undefined ? d.content : d);
578
41
  });
579
42
  }
580
- }`;
581
- const loader = {
582
- ".tsx": "tsx",
583
- ".jsx": "jsx"
584
- };
585
- const stdinLoader = filename.endsWith(".tsx") ? "tsx" : "jsx";
586
- const alias = {};
587
- try {
588
- const nodePath = require("path");
589
- const nodeFs = require("fs");
590
- const candidates = [
591
- nodePath.join(process.cwd(), "node_modules", "@frontmcp", "ui", "dist", "esm"),
592
- nodePath.join(resolveDir, "node_modules", "@frontmcp", "ui", "dist", "esm")
593
- ];
594
- for (const uiEsmBase of candidates) {
595
- if (!nodeFs.existsSync(uiEsmBase)) continue;
596
- const subpaths = ["components", "react", "theme", "bridge", "runtime"];
597
- for (const sub of subpaths) {
598
- const mjs = nodePath.join(uiEsmBase, sub, "index.mjs");
599
- if (nodeFs.existsSync(mjs)) alias[`@frontmcp/ui/${sub}`] = mjs;
600
- }
601
- if (Object.keys(alias).length > 0) break;
602
- }
603
- } catch {
604
- }
605
- try {
606
- const result = esbuild.buildSync({
607
- stdin: {
608
- contents: source + "\n" + mountCode,
609
- loader: stdinLoader,
610
- resolveDir,
611
- sourcefile: filename
612
- },
613
- bundle: true,
614
- write: false,
615
- format: "esm",
616
- target: "es2020",
617
- jsx: "automatic",
618
- // When `bundleReact` is set (resourceMode: 'inline'), React itself is
619
- // bundled — required for hosts that block external script execution
620
- // such as Claude (#454). Otherwise React stays external and is loaded
621
- // via the import map emitted by the renderer.
622
- external: options.bundleReact ? [] : ["react", "react-dom", "react/jsx-runtime", "react/jsx-dev-runtime"],
623
- alias,
624
- define: { "process.env.NODE_ENV": '"production"' },
625
- platform: "browser",
626
- treeShaking: true,
627
- logLevel: "warning",
628
- loader
629
- });
630
- return { code: result.outputFiles[0].text };
631
- } catch (err) {
632
- const message = err instanceof Error ? err.message : String(err);
633
- throw new Error(
634
- `Failed to bundle FileSource "${filename}": ${message}. If the error mentions @frontmcp/ui or @frontmcp/uipack, ensure both packages are installed in the consuming project.`,
635
- { cause: err }
636
- );
637
- }
638
- }
639
- function extractDefaultExportName(code) {
640
- let match = code.match(/export\s+default\s+(?:function|class)\s+(\w+)/);
641
- if (match) return match[1];
642
- match = code.match(/export\s+default\s+(\w+)\s*;/);
643
- if (match) return match[1];
644
- return null;
645
- }
646
-
647
- // libs/uipack/src/component/loader.ts
648
- var DEFAULT_META = {
649
- mcpAware: false,
650
- renderer: "auto"
651
- };
652
- function resolveUISource(source, options) {
653
- if (options?.inlineReact && options?.transformOnly) {
654
- throw new Error("resolveUISource: `inlineReact` and `transformOnly` are mutually exclusive \u2014 set at most one.");
655
- }
656
- const resolver = options?.resolver ?? createEsmShResolver();
657
- if (isNpmSource(source)) {
658
- return resolveNpmSource(source, resolver);
659
- }
660
- if (isImportSource(source)) {
661
- return resolveImportSource(source);
662
- }
663
- if (isFileSource(source)) {
664
- return resolveFileSource(source, { inlineReact: options?.inlineReact, transformOnly: options?.transformOnly });
665
- }
666
- if (isFunctionSource(source)) {
667
- return resolveFunctionSource(source, options?.input, options?.output);
668
- }
669
- throw new Error("Unknown UISource type");
670
- }
671
- function resolveNpmSource(source, resolver) {
672
- const specifier = source.version ? `${source.npm}@${source.version}` : source.npm;
673
- const pkgName = getPackageName(source.npm);
674
- const resolved = resolver.resolve(specifier);
675
- const url = resolved?.value ?? `https://esm.sh/${specifier}`;
676
- const peerDeps = [];
677
- if (pkgName !== "react" && pkgName !== "react-dom") {
678
- peerDeps.push("react", "react-dom");
679
- }
680
- return {
681
- mode: "module",
682
- url,
683
- exportName: source.exportName ?? "default",
684
- meta: { ...DEFAULT_META, renderer: "react" },
685
- peerDependencies: peerDeps
686
- };
687
- }
688
- function resolveImportSource(source) {
689
- return {
690
- mode: "module",
691
- url: source.import,
692
- exportName: source.exportName ?? "default",
693
- meta: { ...DEFAULT_META },
694
- peerDependencies: []
695
- };
696
- }
697
- var BUILD_DIR_SEGMENTS = /* @__PURE__ */ new Set(["dist", "build", "out"]);
698
- function missingWidgetError(filePath, cause) {
699
- const sourceWidget = findSourceWidget(filePath);
700
- const error = new Error(
701
- `FileSource widget not found (ENOENT): no file at "${filePath}". The widget source is read from this path when the tool is called, so it has to exist where the compiled tool runs \u2014 a path built from \`__dirname\` or \`import.meta.url\` points into the build output once the tool is compiled. tsc does not copy \`*.widget.tsx\` / \`*.widget.jsx\` files into its output; \`frontmcp build\` does, and any other build needs a step that copies them next to the compiled tool.` + (sourceWidget ? ` The source widget exists at "${sourceWidget}" \u2014 copy it to "${filePath}", or build with \`frontmcp build\`.` : ""),
702
- { cause }
703
- );
704
- error.code = "ENOENT";
705
- error.path = filePath;
706
- return error;
707
- }
708
- function findSourceWidget(filePath) {
709
- const path = require("path");
710
- const fs = require("fs");
711
- const parts = filePath.split(path.sep);
712
- for (let i = parts.length - 2; i >= 0; i--) {
713
- if (!BUILD_DIR_SEGMENTS.has(parts[i])) continue;
714
- const candidates = [[...parts.slice(0, i), "src", ...parts.slice(i + 1)]];
715
- if (parts.length - i > 2) candidates.push([...parts.slice(0, i), "src", ...parts.slice(i + 2)]);
716
- candidates.push([...parts.slice(0, i), ...parts.slice(i + 1)]);
717
- for (const candidate of candidates) {
718
- const candidatePath = candidate.join(path.sep);
719
- try {
720
- if (fs.existsSync(candidatePath)) return candidatePath;
721
- } catch {
722
- }
723
- }
724
- return void 0;
725
- }
726
- return void 0;
727
- }
728
- function resolveFileSource(source, options = {}) {
729
- const path = require("path");
730
- const ext = path.extname(source.file).toLowerCase();
731
- if (ext === ".tsx" || ext === ".jsx") {
732
- const fs = require("fs");
733
- const wasRelative = !path.isAbsolute(source.file);
734
- const filePath = wasRelative ? path.resolve(process.cwd(), source.file) : source.file;
735
- let rawSource;
736
- try {
737
- rawSource = fs.readFileSync(filePath, "utf-8");
738
- } catch (err) {
739
- const isNotFound = err?.code === "ENOENT";
740
- if (isNotFound && wasRelative) {
741
- throw new Error(
742
- `FileSource widget "${source.file}" not found at "${filePath}". Relative paths are resolved against process.cwd() ("${process.cwd()}"), not the tool file's directory. To anchor the path to the tool file, pass an absolute path \u2014 e.g. \`{ file: fileURLToPath(new URL('./widget.tsx', import.meta.url)) }\` from \`node:url\` (see issue #444).`,
743
- { cause: err }
744
- );
745
- }
746
- if (isNotFound) throw missingWidgetError(filePath, err);
747
- throw err;
748
- }
749
- const componentName = source.exportName || extractDefaultExportName(rawSource) || "Component";
750
- if (options.transformOnly === true) {
751
- const code = transpileReactSource(rawSource, path.basename(filePath));
752
- const parsed2 = parseImports(code);
753
- return {
754
- mode: "module",
755
- code,
756
- imports: [...new Set(parsed2.externalImports.map((i) => i.specifier))],
757
- exportName: componentName,
758
- meta: { mcpAware: true, renderer: "react" },
759
- peerDependencies: source.peerDependencies || ["react", "react-dom"],
760
- bundled: false
761
- };
762
- }
763
- const bundled = bundleFileSource(rawSource, source.file, path.dirname(filePath), componentName, {
764
- bundleReact: options.inlineReact === true
765
- });
766
- const parsed = parseImports(bundled.code);
767
- return {
768
- mode: "module",
769
- code: bundled.code,
770
- imports: [...new Set(parsed.externalImports.map((i) => i.specifier))],
771
- exportName: componentName,
772
- meta: { mcpAware: true, renderer: "react" },
773
- peerDependencies: source.peerDependencies || ["react", "react-dom"],
774
- bundled: true
775
- };
776
- }
777
- if (source.inline) {
778
- return {
779
- mode: "inline",
780
- html: `<!-- File source: ${source.file} (inline mode - content to be resolved at build time) -->`,
781
- exportName: "default",
782
- meta: { ...DEFAULT_META, renderer: "html" },
783
- peerDependencies: []
784
- };
785
- }
786
- return {
787
- mode: "module",
788
- url: source.file,
789
- exportName: "default",
790
- meta: { ...DEFAULT_META },
791
- peerDependencies: []
792
- };
793
- }
794
- function resolveFunctionSource(source, input, output) {
795
- const html = source(input, output);
796
- return {
797
- mode: "inline",
798
- html,
799
- exportName: "default",
800
- meta: { mcpAware: false, renderer: "html" },
801
- peerDependencies: []
802
- };
803
- }
804
- function generateMountScript(resolved, propsMapping) {
805
- if (resolved.mode !== "module" || !resolved.url) {
806
- return "";
807
- }
808
- const componentImport = resolved.exportName === "default" ? `import Component from '${resolved.url}';` : `import { ${resolved.exportName} as Component } from '${resolved.url}';`;
809
- if (resolved.meta.mcpAware) {
810
- return `${componentImport}
43
+ }`;const loader={".tsx":"tsx",".jsx":"jsx"};const stdinLoader=filename.endsWith(".tsx")?"tsx":"jsx";const alias={};try{const nodePath=require("path");const nodeFs=require("fs");const candidates=[nodePath.join(process.cwd(),"node_modules","@frontmcp","ui","dist","esm"),nodePath.join(resolveDir,"node_modules","@frontmcp","ui","dist","esm")];for(const uiEsmBase of candidates){if(!nodeFs.existsSync(uiEsmBase))continue;const subpaths=["components","react","theme","bridge","runtime"];for(const sub of subpaths){const mjs=nodePath.join(uiEsmBase,sub,"index.mjs");if(nodeFs.existsSync(mjs))alias[`@frontmcp/ui/${sub}`]=mjs}if(Object.keys(alias).length>0)break}}catch{}try{const result=esbuild.buildSync({stdin:{contents:source+"\n"+mountCode,loader:stdinLoader,resolveDir,sourcefile:filename},bundle:true,write:false,format:"esm",target:"es2020",jsx:"automatic",external:options.bundleReact?[]:["react","react-dom","react/jsx-runtime","react/jsx-dev-runtime"],alias,define:{"process.env.NODE_ENV":'"production"'},platform:"browser",treeShaking:true,logLevel:"warning",loader});return{code:result.outputFiles[0].text}}catch(err){const message=err instanceof Error?err.message:String(err);throw new Error(`Failed to bundle FileSource "${filename}": ${message}. If the error mentions @frontmcp/ui or @frontmcp/uipack, ensure both packages are installed in the consuming project.`,{cause:err})}}function extractDefaultExportName(code){let match=code.match(/export\s+default\s+(?:function|class)\s+(\w+)/);if(match)return match[1];match=code.match(/export\s+default\s+(\w+)\s*;/);if(match)return match[1];return null}var DEFAULT_META={mcpAware:false,renderer:"auto"};function resolveUISource(source,options){if(options?.inlineReact&&options?.transformOnly){throw new Error("resolveUISource: `inlineReact` and `transformOnly` are mutually exclusive \u2014 set at most one.")}const resolver=options?.resolver??createEsmShResolver();if(isNpmSource(source)){return resolveNpmSource(source,resolver)}if(isImportSource(source)){return resolveImportSource(source)}if(isFileSource(source)){return resolveFileSource(source,{inlineReact:options?.inlineReact,transformOnly:options?.transformOnly})}if(isFunctionSource(source)){return resolveFunctionSource(source,options?.input,options?.output)}throw new Error("Unknown UISource type")}function resolveNpmSource(source,resolver){const specifier=source.version?`${source.npm}@${source.version}`:source.npm;const pkgName=getPackageName(source.npm);const resolved=resolver.resolve(specifier);const url=resolved?.value??`https://esm.sh/${specifier}`;const peerDeps=[];if(pkgName!=="react"&&pkgName!=="react-dom"){peerDeps.push("react","react-dom")}return{mode:"module",url,exportName:source.exportName??"default",meta:{...DEFAULT_META,renderer:"react"},peerDependencies:peerDeps}}function resolveImportSource(source){return{mode:"module",url:source.import,exportName:source.exportName??"default",meta:{...DEFAULT_META},peerDependencies:[]}}var BUILD_DIR_SEGMENTS=new Set(["dist","build","out"]);function missingWidgetError(filePath,cause){const sourceWidget=findSourceWidget(filePath);const error=new Error(`FileSource widget not found (ENOENT): no file at "${filePath}". The widget source is read from this path when the tool is called, so it has to exist where the compiled tool runs \u2014 a path built from \`__dirname\` or \`import.meta.url\` points into the build output once the tool is compiled. tsc does not copy \`*.widget.tsx\` / \`*.widget.jsx\` files into its output; \`frontmcp build\` does, and any other build needs a step that copies them next to the compiled tool.`+(sourceWidget?` The source widget exists at "${sourceWidget}" \u2014 copy it to "${filePath}", or build with \`frontmcp build\`.`:""),{cause});error.code="ENOENT";error.path=filePath;return error}function findSourceWidget(filePath){const path=require("path");const fs=require("fs");const parts=filePath.split(path.sep);for(let i=parts.length-2;i>=0;i--){if(!BUILD_DIR_SEGMENTS.has(parts[i]))continue;const candidates=[[...parts.slice(0,i),"src",...parts.slice(i+1)]];if(parts.length-i>2)candidates.push([...parts.slice(0,i),"src",...parts.slice(i+2)]);candidates.push([...parts.slice(0,i),...parts.slice(i+1)]);for(const candidate of candidates){const candidatePath=candidate.join(path.sep);try{if(fs.existsSync(candidatePath))return candidatePath}catch{}}return void 0}return void 0}function resolveFileSource(source,options={}){const path=require("path");const ext=path.extname(source.file).toLowerCase();if(ext===".tsx"||ext===".jsx"){const fs=require("fs");const wasRelative=!path.isAbsolute(source.file);const filePath=wasRelative?path.resolve(process.cwd(),source.file):source.file;let rawSource;try{rawSource=fs.readFileSync(filePath,"utf-8")}catch(err){const isNotFound=err?.code==="ENOENT";if(isNotFound&&wasRelative){throw new Error(`FileSource widget "${source.file}" not found at "${filePath}". Relative paths are resolved against process.cwd() ("${process.cwd()}"), not the tool file's directory. To anchor the path to the tool file, pass an absolute path \u2014 e.g. \`{ file: fileURLToPath(new URL('./widget.tsx', import.meta.url)) }\` from \`node:url\` (see issue #444).`,{cause:err})}if(isNotFound)throw missingWidgetError(filePath,err);throw err}const componentName=source.exportName||extractDefaultExportName(rawSource)||"Component";if(options.transformOnly===true){const code=transpileReactSource(rawSource,path.basename(filePath));const parsed2=parseImports(code);return{mode:"module",code,imports:[...new Set(parsed2.externalImports.map(i=>i.specifier))],exportName:componentName,meta:{mcpAware:true,renderer:"react"},peerDependencies:source.peerDependencies||["react","react-dom"],bundled:false}}const bundled=bundleFileSource(rawSource,source.file,path.dirname(filePath),componentName,{bundleReact:options.inlineReact===true});const parsed=parseImports(bundled.code);return{mode:"module",code:bundled.code,imports:[...new Set(parsed.externalImports.map(i=>i.specifier))],exportName:componentName,meta:{mcpAware:true,renderer:"react"},peerDependencies:source.peerDependencies||["react","react-dom"],bundled:true}}if(source.inline){return{mode:"inline",html:`<!-- File source: ${source.file} (inline mode - content to be resolved at build time) -->`,exportName:"default",meta:{...DEFAULT_META,renderer:"html"},peerDependencies:[]}}return{mode:"module",url:source.file,exportName:"default",meta:{...DEFAULT_META},peerDependencies:[]}}function resolveFunctionSource(source,input,output){const html=source(input,output);return{mode:"inline",html,exportName:"default",meta:{mcpAware:false,renderer:"html"},peerDependencies:[]}}function generateMountScript(resolved,propsMapping){if(resolved.mode!=="module"||!resolved.url){return""}const componentImport=resolved.exportName==="default"?`import Component from '${resolved.url}';`:`import { ${resolved.exportName} as Component } from '${resolved.url}';`;if(resolved.meta.mcpAware){return`${componentImport}
811
44
  import React from 'react';
812
45
  import { createRoot } from 'react-dom/client';
813
46
  createRoot(document.getElementById('root'))
814
- .render(React.createElement(Component));`;
815
- }
816
- const propsCode = propsMapping ? generateMappedPropsCode(propsMapping) : "window.__mcpToolOutput";
817
- return `${componentImport}
47
+ .render(React.createElement(Component));`}const propsCode=propsMapping?generateMappedPropsCode(propsMapping):"window.__mcpToolOutput";return`${componentImport}
818
48
  import React from 'react';
819
49
  import { createRoot } from 'react-dom/client';
820
50
  const output = window.__mcpToolOutput || {};
821
51
  const props = ${propsCode};
822
52
  createRoot(document.getElementById('root'))
823
- .render(React.createElement(Component, props));`;
824
- }
825
- function generateMappedPropsCode(mapping) {
826
- const entries = Object.entries(mapping).map(([prop, path]) => {
827
- const accessPath = path.split(".").map((part) => `[${safeJsonForScript(part)}]`).join("");
828
- return `${safeJsonForScript(prop)}: output${accessPath}`;
829
- }).join(", ");
830
- return `({ ${entries} })`;
831
- }
832
-
833
- // libs/uipack/src/resolver/import-map.ts
834
- function createImportMapFromResolved(resolved) {
835
- const imports = {};
836
- const integrity = {};
837
- for (const [specifier, res] of Object.entries(resolved)) {
838
- if (res.type === "url") {
839
- imports[specifier] = res.value;
840
- if (res.integrity) {
841
- integrity[res.value] = res.integrity;
842
- }
843
- }
844
- }
845
- return {
846
- imports,
847
- integrity: Object.keys(integrity).length > 0 ? integrity : void 0
848
- };
849
- }
850
- function generateImportMapScriptTag(map) {
851
- const json = JSON.stringify(map, null, 2).replace(/<\//g, "<\\/");
852
- return `<script type="importmap">
53
+ .render(React.createElement(Component, props));`}function generateMappedPropsCode(mapping){const entries=Object.entries(mapping).map(([prop,path])=>{const accessPath=path.split(".").map(part=>`[${safeJsonForScript(part)}]`).join("");return`${safeJsonForScript(prop)}: output${accessPath}`}).join(", ");return`({ ${entries} })`}function createImportMapFromResolved(resolved){const imports={};const integrity={};for(const[specifier,res]of Object.entries(resolved)){if(res.type==="url"){imports[specifier]=res.value;if(res.integrity){integrity[res.value]=res.integrity}}}return{imports,integrity:Object.keys(integrity).length>0?integrity:void 0}}function generateImportMapScriptTag(map){const json=JSON.stringify(map,null,2).replace(/<\//g,"<\\/");return`<script type="importmap">
853
54
  ${json}
854
- </script>`;
855
- }
856
-
857
- // libs/uipack/src/bridge-runtime/iife-generator.ts
858
- var WIDGET_CALL_META_KEY = "frontmcp/widgetCall";
859
- var MCP_APPS_DISPLAY_MODES = ["inline", "fullscreen", "pip"];
860
- function generateBridgeIIFE(options = {}) {
861
- const { debug = false, trustedOrigins = [], minify = false } = options;
862
- const adapters = options.adapters || ["openai", "ext-apps", "claude", "gemini", "generic"];
863
- const parts = [];
864
- parts.push("(function() {");
865
- parts.push('"use strict";');
866
- parts.push("");
867
- if (debug) {
868
- parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }');
869
- } else {
870
- parts.push("function log() {}");
871
- }
872
- parts.push("");
873
- parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");
874
- parts.push("");
875
- parts.push(generateContextDetection());
876
- parts.push("");
877
- parts.push(generateBaseCapabilities());
878
- parts.push("");
879
- if (adapters.includes("openai")) {
880
- parts.push(generateOpenAIAdapter());
881
- parts.push("");
882
- }
883
- if (adapters.includes("ext-apps")) {
884
- parts.push(generateExtAppsAdapter(trustedOrigins));
885
- parts.push("");
886
- }
887
- if (adapters.includes("claude")) {
888
- parts.push(generateClaudeAdapter());
889
- parts.push("");
890
- }
891
- if (adapters.includes("gemini")) {
892
- parts.push(generateGeminiAdapter());
893
- parts.push("");
894
- }
895
- if (adapters.includes("generic")) {
896
- parts.push(generateGenericAdapter());
897
- parts.push("");
898
- }
899
- parts.push(generatePlatformDetection(adapters));
900
- parts.push("");
901
- parts.push(generateBridgeClass());
902
- parts.push("");
903
- parts.push("var bridge = new FrontMcpBridge();");
904
- parts.push("bridge.initialize().then(function() {");
905
- parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');
906
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');
907
- parts.push(" if (window.__mcpDisplayMode) bridge.requestDisplayMode(window.__mcpDisplayMode).catch(function() {});");
908
- parts.push("}).catch(function(err) {");
909
- parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');
910
- parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');
911
- parts.push("});");
912
- parts.push("");
913
- parts.push("window.FrontMcpBridge = bridge;");
914
- parts.push("");
915
- parts.push(generateAutoResize());
916
- parts.push("function __showLoading() {");
917
- parts.push(' var root = document.getElementById("root");');
918
- parts.push(" if (root && !root.hasChildNodes()) {");
919
- parts.push(
920
- ` root.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;padding:2rem;color:#6b7280;font-family:system-ui,sans-serif"><div style="text-align:center"><div style="width:24px;height:24px;border:2px solid #e5e7eb;border-top-color:#3b82f6;border-radius:50%;animation:__spin 0.6s linear infinite;margin:0 auto 12px"></div><div style="font-size:0.875rem">Loading widget...</div></div></div><style>@keyframes __spin{to{transform:rotate(360deg)}}</style>';`
921
- );
922
- parts.push(" }");
923
- parts.push("}");
924
- parts.push('if (document.readyState === "loading") {');
925
- parts.push(' document.addEventListener("DOMContentLoaded", __showLoading);');
926
- parts.push("} else {");
927
- parts.push(" __showLoading();");
928
- parts.push("}");
929
- parts.push("})();");
930
- const code = parts.join("\n");
931
- if (minify) {
932
- return minifyJS(code);
933
- }
934
- return code;
935
- }
936
- function generateAutoResize() {
937
- return `
55
+ </script>`}var WIDGET_CALL_META_KEY="frontmcp/widgetCall";var MCP_APPS_DISPLAY_MODES=["inline","fullscreen","pip"];function generateBridgeIIFE(options={}){const{debug=false,trustedOrigins=[],minify=false}=options;const adapters=options.adapters||["openai","ext-apps","claude","gemini","generic"];const parts=[];parts.push("(function() {");parts.push('"use strict";');parts.push("");if(debug){parts.push('function log(msg) { console.log("[FrontMcpBridge] " + msg); }')}else{parts.push("function log() {}")}parts.push("");parts.push("var DEFAULT_SAFE_AREA = { top: 0, bottom: 0, left: 0, right: 0 };");parts.push("");parts.push(generateContextDetection());parts.push("");parts.push(generateBaseCapabilities());parts.push("");if(adapters.includes("openai")){parts.push(generateOpenAIAdapter());parts.push("")}if(adapters.includes("ext-apps")){parts.push(generateExtAppsAdapter(trustedOrigins));parts.push("")}if(adapters.includes("claude")){parts.push(generateClaudeAdapter());parts.push("")}if(adapters.includes("gemini")){parts.push(generateGeminiAdapter());parts.push("")}if(adapters.includes("generic")){parts.push(generateGenericAdapter());parts.push("")}parts.push(generatePlatformDetection(adapters));parts.push("");parts.push(generateBridgeClass());parts.push("");parts.push("var bridge = new FrontMcpBridge();");parts.push("bridge.initialize().then(function() {");parts.push(' log("Bridge initialized with adapter: " + bridge.adapterId);');parts.push(' window.dispatchEvent(new CustomEvent("bridge:ready", { detail: { adapter: bridge.adapterId } }));');parts.push(" if (window.__mcpDisplayMode) bridge.requestDisplayMode(window.__mcpDisplayMode).catch(function() {});");parts.push("}).catch(function(err) {");parts.push(' console.error("[FrontMcpBridge] Init failed:", err);');parts.push(' window.dispatchEvent(new CustomEvent("bridge:error", { detail: { error: err } }));');parts.push("});");parts.push("");parts.push("window.FrontMcpBridge = bridge;");parts.push("");parts.push(generateAutoResize());parts.push("function __showLoading() {");parts.push(' var root = document.getElementById("root");');parts.push(" if (root && !root.hasChildNodes()) {");parts.push(` root.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;padding:2rem;color:#6b7280;font-family:system-ui,sans-serif"><div style="text-align:center"><div style="width:24px;height:24px;border:2px solid #e5e7eb;border-top-color:#3b82f6;border-radius:50%;animation:__spin 0.6s linear infinite;margin:0 auto 12px"></div><div style="font-size:0.875rem">Loading widget...</div></div></div><style>@keyframes __spin{to{transform:rotate(360deg)}}</style>';`);parts.push(" }");parts.push("}");parts.push('if (document.readyState === "loading") {');parts.push(' document.addEventListener("DOMContentLoaded", __showLoading);');parts.push("} else {");parts.push(" __showLoading();");parts.push("}");parts.push("})();");const code=parts.join("\n");if(minify){return minifyJS(code)}return code}function generateAutoResize(){return`
938
56
  function __applySizingCss(sizing) {
939
57
  if (typeof document === 'undefined' || !document.documentElement) return;
940
58
  function toLen(v) { return typeof v === 'number' ? v + 'px' : v; }
@@ -1069,10 +187,7 @@ function __initAutoResize() {
1069
187
  }
1070
188
  }
1071
189
  __initAutoResize();
1072
- `.trim();
1073
- }
1074
- function generateContextDetection() {
1075
- return `
190
+ `.trim()}function generateContextDetection(){return`
1076
191
  function detectTheme() {
1077
192
  if (typeof window !== 'undefined' && window.matchMedia) {
1078
193
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
@@ -1159,10 +274,7 @@ function readInjectedData() {
1159
274
  }
1160
275
  return data;
1161
276
  }
1162
- `.trim();
1163
- }
1164
- function generateBaseCapabilities() {
1165
- return `
277
+ `.trim()}function generateBaseCapabilities(){return`
1166
278
  var DEFAULT_CAPABILITIES = {
1167
279
  canCallTools: false,
1168
280
  canSendMessages: false,
@@ -1172,10 +284,7 @@ var DEFAULT_CAPABILITIES = {
1172
284
  supportsDisplayModes: false,
1173
285
  supportsTheme: true
1174
286
  };
1175
- `.trim();
1176
- }
1177
- function generateOpenAIAdapter() {
1178
- return `
287
+ `.trim()}function generateOpenAIAdapter(){return`
1179
288
  var OpenAIAdapter = {
1180
289
  id: 'openai',
1181
290
  name: 'OpenAI ChatGPT',
@@ -1260,11 +369,7 @@ var OpenAIAdapter = {
1260
369
  return Promise.resolve();
1261
370
  }
1262
371
  };
1263
- `.trim();
1264
- }
1265
- function generateExtAppsAdapter(trustedOrigins) {
1266
- const originsArray = trustedOrigins.length > 0 ? JSON.stringify(trustedOrigins) : "[]";
1267
- return `
372
+ `.trim()}function generateExtAppsAdapter(trustedOrigins){const originsArray=trustedOrigins.length>0?JSON.stringify(trustedOrigins):"[]";return`
1268
373
  var ExtAppsAdapter = {
1269
374
  id: 'ext-apps',
1270
375
  name: 'ext-apps (SEP-1865)',
@@ -1607,10 +712,7 @@ var ExtAppsAdapter = {
1607
712
  return this.sendRequest('ui/unregisterTool', { name: name });
1608
713
  }
1609
714
  };
1610
- `.trim();
1611
- }
1612
- function generateClaudeAdapter() {
1613
- return `
715
+ `.trim()}function generateClaudeAdapter(){return`
1614
716
  var ClaudeAdapter = {
1615
717
  id: 'claude',
1616
718
  name: 'Claude (Anthropic)',
@@ -1671,10 +773,7 @@ var ClaudeAdapter = {
1671
773
  return Promise.resolve();
1672
774
  }
1673
775
  };
1674
- `.trim();
1675
- }
1676
- function generateGeminiAdapter() {
1677
- return `
776
+ `.trim()}function generateGeminiAdapter(){return`
1678
777
  var GeminiAdapter = {
1679
778
  id: 'gemini',
1680
779
  name: 'Google Gemini',
@@ -1725,10 +824,7 @@ var GeminiAdapter = {
1725
824
  return Promise.resolve();
1726
825
  }
1727
826
  };
1728
- `.trim();
1729
- }
1730
- function generateGenericAdapter() {
1731
- return `
827
+ `.trim()}function generateGenericAdapter(){return`
1732
828
  var GenericAdapter = {
1733
829
  id: 'generic',
1734
830
  name: 'Generic Web',
@@ -1763,26 +859,7 @@ var GenericAdapter = {
1763
859
  return Promise.resolve();
1764
860
  }
1765
861
  };
1766
- `.trim();
1767
- }
1768
- function generatePlatformDetection(adapters) {
1769
- const adapterVars = adapters.map((a) => {
1770
- switch (a) {
1771
- case "openai":
1772
- return "OpenAIAdapter";
1773
- case "ext-apps":
1774
- return "ExtAppsAdapter";
1775
- case "claude":
1776
- return "ClaudeAdapter";
1777
- case "gemini":
1778
- return "GeminiAdapter";
1779
- case "generic":
1780
- return "GenericAdapter";
1781
- default:
1782
- return "";
1783
- }
1784
- }).filter(Boolean);
1785
- return `
862
+ `.trim()}function generatePlatformDetection(adapters){const adapterVars=adapters.map(a=>{switch(a){case"openai":return"OpenAIAdapter";case"ext-apps":return"ExtAppsAdapter";case"claude":return"ClaudeAdapter";case"gemini":return"GeminiAdapter";case"generic":return"GenericAdapter";default:return""}}).filter(Boolean);return`
1786
863
  var ADAPTERS = [${adapterVars.join(", ")}].sort(function(a, b) { return b.priority - a.priority; });
1787
864
 
1788
865
  function detectPlatform() {
@@ -1795,10 +872,7 @@ function detectPlatform() {
1795
872
  log('No platform detected, using generic');
1796
873
  return GenericAdapter;
1797
874
  }
1798
- `.trim();
1799
- }
1800
- function generateBridgeClass() {
1801
- return `
875
+ `.trim()}function generateBridgeClass(){return`
1802
876
  function FrontMcpBridge() {
1803
877
  this._adapter = null;
1804
878
  this._initialized = false;
@@ -2174,530 +1248,26 @@ FrontMcpBridge.prototype._setupDataToolCallHandler = function() {
2174
1248
  }
2175
1249
  }, true); // Use capture phase to handle before React handlers
2176
1250
  };
2177
- `.trim();
2178
- }
2179
- var MAX_MINIFY_CODE_LENGTH = 5e5;
2180
- function minifyJS(code) {
2181
- if (code.length > MAX_MINIFY_CODE_LENGTH) {
2182
- return code;
2183
- }
2184
- const out = [];
2185
- let inBlockComment = false;
2186
- for (const raw of code.split("\n")) {
2187
- const line = raw.trim();
2188
- if (inBlockComment) {
2189
- if (line.includes("*/")) inBlockComment = false;
2190
- continue;
2191
- }
2192
- if (line === "" || line.startsWith("//")) continue;
2193
- if (line.startsWith("/*")) {
2194
- if (!line.includes("*/")) inBlockComment = true;
2195
- continue;
2196
- }
2197
- out.push(line);
2198
- }
2199
- return out.join("\n");
2200
- }
2201
- function generatePlatformBundle(platform, options = {}) {
2202
- const platformAdapters = {
2203
- chatgpt: ["openai", "generic"],
2204
- claude: ["claude", "generic"],
2205
- gemini: ["gemini", "generic"],
2206
- universal: ["openai", "ext-apps", "claude", "gemini", "generic"]
2207
- };
2208
- return generateBridgeIIFE({
2209
- ...options,
2210
- adapters: platformAdapters[platform]
2211
- });
2212
- }
2213
- var UNIVERSAL_BRIDGE_SCRIPT = generateBridgeIIFE();
2214
- var BRIDGE_SCRIPT_TAGS = {
2215
- universal: `<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,
2216
- chatgpt: `<script>${generatePlatformBundle("chatgpt")}</script>`,
2217
- claude: `<script>${generatePlatformBundle("claude")}</script>`,
2218
- gemini: `<script>${generatePlatformBundle("gemini")}</script>`
2219
- };
2220
-
2221
- // libs/uipack/src/shell/csp.ts
2222
- var DEFAULT_CDN_DOMAINS = [
2223
- "https://cdn.jsdelivr.net",
2224
- "https://cdnjs.cloudflare.com",
2225
- "https://fonts.googleapis.com",
2226
- "https://fonts.gstatic.com",
2227
- "https://esm.sh"
2228
- ];
2229
- var DEFAULT_CSP_DIRECTIVES = [
2230
- "default-src 'none'",
2231
- `script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2232
- `style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2233
- `img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2234
- `font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2235
- `connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,
2236
- "object-src 'self' data:"
2237
- ];
2238
- function buildCSPDirectives(csp) {
2239
- if (!csp) {
2240
- return [...DEFAULT_CSP_DIRECTIVES];
2241
- }
2242
- const validResourceDomains = sanitizeCSPDomains(csp.resourceDomains);
2243
- const validConnectDomains = sanitizeCSPDomains(csp.connectDomains);
2244
- const allResourceDomains = [.../* @__PURE__ */ new Set([...DEFAULT_CDN_DOMAINS, ...validResourceDomains])];
2245
- const directives = [
2246
- "default-src 'none'",
2247
- `script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,
2248
- `style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`
2249
- ];
2250
- const imgSources = ["'self'", "data:", ...allResourceDomains];
2251
- directives.push(`img-src ${imgSources.join(" ")}`);
2252
- const fontSources = ["'self'", "data:", ...allResourceDomains];
2253
- directives.push(`font-src ${fontSources.join(" ")}`);
2254
- const connectSources = [.../* @__PURE__ */ new Set([...allResourceDomains, ...validConnectDomains])];
2255
- directives.push(`connect-src ${connectSources.join(" ")}`);
2256
- directives.push("object-src 'self' data:");
2257
- return directives;
2258
- }
2259
- function buildCSPMetaTag(csp) {
2260
- const directives = buildCSPDirectives(csp);
2261
- const content = directives.join("; ");
2262
- return `<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`;
2263
- }
2264
- var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
2265
- function validateCSPDomain(domain) {
2266
- if (typeof domain !== "string" || /[\s;,'"]/.test(domain)) return false;
2267
- if (/[?#]/.test(domain)) return false;
2268
- if (domain.includes("*")) {
2269
- const wildcard = /^(?:https|wss):\/\/\*\.(.*)$/.exec(domain);
2270
- return wildcard !== null && /^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(wildcard[1]);
2271
- }
2272
- try {
2273
- const url = new URL(domain);
2274
- if (url.protocol === "https:" || url.protocol === "wss:") return true;
2275
- return (url.protocol === "http:" || url.protocol === "ws:") && LOOPBACK_HOSTS.has(url.hostname);
2276
- } catch {
2277
- return false;
2278
- }
2279
- }
2280
- var reportedInvalidDomains = /* @__PURE__ */ new Set();
2281
- function sanitizeCSPDomains(domains) {
2282
- if (!domains) return [];
2283
- const valid = [];
2284
- for (const domain of domains) {
2285
- if (validateCSPDomain(domain)) {
2286
- valid.push(domain);
2287
- } else if (!reportedInvalidDomains.has(domain)) {
2288
- reportedInvalidDomains.add(domain);
2289
- console.warn(
2290
- `Invalid CSP domain ignored: ${domain} (expected an https:// or wss:// origin, or http:// / ws:// on localhost)`
2291
- );
2292
- }
2293
- }
2294
- return valid;
2295
- }
2296
- function escapeAttribute(str) {
2297
- return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2298
- }
2299
-
2300
- // libs/uipack/src/shell/custom-shell-types.ts
2301
- var SHELL_PLACEHOLDER_NAMES = ["CSP", "DATA", "BRIDGE", "CONTENT", "TITLE"];
2302
- var SHELL_PLACEHOLDERS = {
2303
- CSP: "{{CSP}}",
2304
- DATA: "{{DATA}}",
2305
- BRIDGE: "{{BRIDGE}}",
2306
- CONTENT: "{{CONTENT}}",
2307
- TITLE: "{{TITLE}}"
2308
- };
2309
- var REQUIRED_PLACEHOLDERS = ["CONTENT"];
2310
- var OPTIONAL_PLACEHOLDERS = ["CSP", "DATA", "BRIDGE", "TITLE"];
2311
-
2312
- // libs/uipack/src/shell/custom-shell-applier.ts
2313
- var PLACEHOLDER_PATTERN = new RegExp(`\\{\\{(${SHELL_PLACEHOLDER_NAMES.join("|")})\\}\\}`, "g");
2314
- var VALUE_KEYS = {
2315
- CSP: "csp",
2316
- DATA: "data",
2317
- BRIDGE: "bridge",
2318
- CONTENT: "content",
2319
- TITLE: "title"
2320
- };
2321
- function applyShellTemplate(template, values) {
2322
- return template.replace(PLACEHOLDER_PATTERN, (_token, name) => values[VALUE_KEYS[name]]);
2323
- }
2324
-
2325
- // libs/uipack/src/shell/custom-shell-validator.ts
2326
- function validateShellTemplate(template) {
2327
- const found = {};
2328
- for (const name of SHELL_PLACEHOLDER_NAMES) {
2329
- found[name] = template.includes(SHELL_PLACEHOLDERS[name]);
2330
- }
2331
- const missingRequired = REQUIRED_PLACEHOLDERS.filter((name) => !found[name]);
2332
- const missingOptional = OPTIONAL_PLACEHOLDERS.filter((name) => !found[name]);
2333
- return {
2334
- valid: missingRequired.length === 0,
2335
- found,
2336
- missingRequired,
2337
- missingOptional
2338
- };
2339
- }
2340
-
2341
- // libs/uipack/src/shell/data-injector.ts
2342
- function hasSizing(sizing) {
2343
- if (!sizing) return false;
2344
- return sizing.preferredHeight !== void 0 || sizing.minHeight !== void 0 || sizing.maxHeight !== void 0 || sizing.aspectRatio !== void 0 || sizing.autoResize !== void 0;
2345
- }
2346
- function buildDataInjectionScript(options) {
2347
- const { toolName, input, output, structuredContent, sizing, displayMode } = options;
2348
- const lines = [
2349
- `window.__mcpAppsEnabled = true;`,
2350
- `window.__mcpToolName = ${safeJsonForScript(toolName)};`,
2351
- `window.__mcpToolInput = ${safeJsonForScript(input ?? null)};`,
2352
- `window.__mcpToolOutput = ${safeJsonForScript(output ?? null)};`,
2353
- `window.__mcpStructuredContent = ${safeJsonForScript(structuredContent ?? null)};`
2354
- ];
2355
- if (hasSizing(sizing)) {
2356
- lines.push(`window.__mcpWidgetSizing = ${safeJsonForScript(sizing)};`);
2357
- }
2358
- if (displayMode && displayMode !== "inline") {
2359
- lines.push(`window.__mcpDisplayMode = ${safeJsonForScript(displayMode)};`);
2360
- }
2361
- return `<script>
1251
+ `.trim()}var MAX_MINIFY_CODE_LENGTH=5e5;function minifyJS(code){if(code.length>MAX_MINIFY_CODE_LENGTH){return code}const out=[];let inBlockComment=false;for(const raw of code.split("\n")){const line=raw.trim();if(inBlockComment){if(line.includes("*/"))inBlockComment=false;continue}if(line===""||line.startsWith("//"))continue;if(line.startsWith("/*")){if(!line.includes("*/"))inBlockComment=true;continue}out.push(line)}return out.join("\n")}function generatePlatformBundle(platform,options={}){const platformAdapters={chatgpt:["openai","generic"],claude:["claude","generic"],gemini:["gemini","generic"],universal:["openai","ext-apps","claude","gemini","generic"]};return generateBridgeIIFE({...options,adapters:platformAdapters[platform]})}var UNIVERSAL_BRIDGE_SCRIPT=generateBridgeIIFE();var BRIDGE_SCRIPT_TAGS={universal:`<script>${UNIVERSAL_BRIDGE_SCRIPT}</script>`,chatgpt:`<script>${generatePlatformBundle("chatgpt")}</script>`,claude:`<script>${generatePlatformBundle("claude")}</script>`,gemini:`<script>${generatePlatformBundle("gemini")}</script>`};var DEFAULT_CDN_DOMAINS=["https://cdn.jsdelivr.net","https://cdnjs.cloudflare.com","https://fonts.googleapis.com","https://fonts.gstatic.com","https://esm.sh"];var DEFAULT_CSP_DIRECTIVES=["default-src 'none'",`script-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,`style-src 'self' 'unsafe-inline' ${DEFAULT_CDN_DOMAINS.join(" ")}`,`img-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,`font-src 'self' data: ${DEFAULT_CDN_DOMAINS.join(" ")}`,`connect-src ${DEFAULT_CDN_DOMAINS.join(" ")}`,"object-src 'self' data:"];function buildCSPDirectives(csp){if(!csp){return[...DEFAULT_CSP_DIRECTIVES]}const validResourceDomains=sanitizeCSPDomains(csp.resourceDomains);const validConnectDomains=sanitizeCSPDomains(csp.connectDomains);const allResourceDomains=[...new Set([...DEFAULT_CDN_DOMAINS,...validResourceDomains])];const directives=["default-src 'none'",`script-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`,`style-src 'self' 'unsafe-inline' ${allResourceDomains.join(" ")}`];const imgSources=["'self'","data:",...allResourceDomains];directives.push(`img-src ${imgSources.join(" ")}`);const fontSources=["'self'","data:",...allResourceDomains];directives.push(`font-src ${fontSources.join(" ")}`);const connectSources=[...new Set([...allResourceDomains,...validConnectDomains])];directives.push(`connect-src ${connectSources.join(" ")}`);directives.push("object-src 'self' data:");return directives}function buildCSPMetaTag(csp){const directives=buildCSPDirectives(csp);const content=directives.join("; ");return`<meta http-equiv="Content-Security-Policy" content="${escapeAttribute(content)}">`}var LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]);function validateCSPDomain(domain){if(typeof domain!=="string"||/[\s;,'"]/.test(domain))return false;if(/[?#]/.test(domain))return false;if(domain.includes("*")){const wildcard=/^(?:https|wss):\/\/\*\.(.*)$/.exec(domain);return wildcard!==null&&/^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/.test(wildcard[1])}try{const url=new URL(domain);if(url.protocol==="https:"||url.protocol==="wss:")return true;return(url.protocol==="http:"||url.protocol==="ws:")&&LOOPBACK_HOSTS.has(url.hostname)}catch{return false}}var reportedInvalidDomains=new Set;function sanitizeCSPDomains(domains){if(!domains)return[];const valid=[];for(const domain of domains){if(validateCSPDomain(domain)){valid.push(domain)}else if(!reportedInvalidDomains.has(domain)){reportedInvalidDomains.add(domain);console.warn(`Invalid CSP domain ignored: ${domain} (expected an https:// or wss:// origin, or http:// / ws:// on localhost)`)}}return valid}function escapeAttribute(str){return str.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var SHELL_PLACEHOLDER_NAMES=["CSP","DATA","BRIDGE","CONTENT","TITLE"];var SHELL_PLACEHOLDERS={CSP:"{{CSP}}",DATA:"{{DATA}}",BRIDGE:"{{BRIDGE}}",CONTENT:"{{CONTENT}}",TITLE:"{{TITLE}}"};var REQUIRED_PLACEHOLDERS=["CONTENT"];var OPTIONAL_PLACEHOLDERS=["CSP","DATA","BRIDGE","TITLE"];var PLACEHOLDER_PATTERN=new RegExp(`\\{\\{(${SHELL_PLACEHOLDER_NAMES.join("|")})\\}\\}`,"g");var VALUE_KEYS={CSP:"csp",DATA:"data",BRIDGE:"bridge",CONTENT:"content",TITLE:"title"};function applyShellTemplate(template,values){return template.replace(PLACEHOLDER_PATTERN,(_token,name)=>values[VALUE_KEYS[name]])}function validateShellTemplate(template){const found={};for(const name of SHELL_PLACEHOLDER_NAMES){found[name]=template.includes(SHELL_PLACEHOLDERS[name])}const missingRequired=REQUIRED_PLACEHOLDERS.filter(name=>!found[name]);const missingOptional=OPTIONAL_PLACEHOLDERS.filter(name=>!found[name]);return{valid:missingRequired.length===0,found,missingRequired,missingOptional}}function hasSizing(sizing){if(!sizing)return false;return sizing.preferredHeight!==void 0||sizing.minHeight!==void 0||sizing.maxHeight!==void 0||sizing.aspectRatio!==void 0||sizing.autoResize!==void 0}function buildDataInjectionScript(options){const{toolName,input,output,structuredContent,sizing,displayMode}=options;const lines=[`window.__mcpAppsEnabled = true;`,`window.__mcpToolName = ${safeJsonForScript(toolName)};`,`window.__mcpToolInput = ${safeJsonForScript(input??null)};`,`window.__mcpToolOutput = ${safeJsonForScript(output??null)};`,`window.__mcpStructuredContent = ${safeJsonForScript(structuredContent??null)};`];if(hasSizing(sizing)){lines.push(`window.__mcpWidgetSizing = ${safeJsonForScript(sizing)};`)}if(displayMode&&displayMode!=="inline"){lines.push(`window.__mcpDisplayMode = ${safeJsonForScript(displayMode)};`)}return`<script>
2362
1252
  ${lines.join("\n")}
2363
- </script>`;
2364
- }
2365
- function buildCustomDataInjectionScript(descriptor) {
2366
- if (descriptor.script !== void 0) {
2367
- return descriptor.script;
2368
- }
2369
- if (descriptor.globalKey !== void 0) {
2370
- return `<script>window[${safeJsonForScript(descriptor.globalKey)}] = ${safeJsonForScript(
2371
- descriptor.value ?? null
2372
- )};</script>`;
2373
- }
2374
- return "";
2375
- }
2376
-
2377
- // libs/uipack/src/shell/sizing-css.ts
2378
- function sanitizeCssValue(value) {
2379
- return value.replace(/[<>{};]/g, "").trim();
2380
- }
2381
- function toCssLength(value) {
2382
- return typeof value === "number" ? `${value}px` : sanitizeCssValue(value);
2383
- }
2384
- function buildSizingStyleTag(sizing) {
2385
- if (!hasSizing(sizing)) return "";
2386
- const hasCssSizing = sizing.preferredHeight !== void 0 || sizing.minHeight !== void 0 || sizing.maxHeight !== void 0 || sizing.aspectRatio !== void 0;
2387
- if (!hasCssSizing) return "";
2388
- const rootRules = [];
2389
- const docRules = ["margin: 0;"];
2390
- if (sizing.preferredHeight !== void 0) {
2391
- const h = toCssLength(sizing.preferredHeight);
2392
- docRules.push(`height: ${h};`);
2393
- rootRules.push(`min-height: ${h};`);
2394
- }
2395
- if (sizing.minHeight !== void 0) {
2396
- const mh = toCssLength(sizing.minHeight);
2397
- docRules.push(`min-height: ${mh};`);
2398
- rootRules.push(`min-height: ${mh};`);
2399
- }
2400
- if (sizing.maxHeight !== void 0) {
2401
- const mx = toCssLength(sizing.maxHeight);
2402
- docRules.push(`max-height: ${mx};`);
2403
- rootRules.push(`max-height: ${mx};`);
2404
- }
2405
- if (sizing.aspectRatio !== void 0) {
2406
- const ar = typeof sizing.aspectRatio === "number" ? String(sizing.aspectRatio) : sanitizeCssValue(sizing.aspectRatio);
2407
- if (ar) rootRules.push(`aspect-ratio: ${ar};`);
2408
- }
2409
- const parts = [`html, body { ${docRules.join(" ")} }`];
2410
- if (rootRules.length > 0) {
2411
- parts.push(`#root { ${rootRules.join(" ")} }`);
2412
- }
2413
- return `<style>${parts.join("\n")}</style>`;
2414
- }
2415
-
2416
- // libs/uipack/src/shell/builder.ts
2417
- function resolveDataInjectionScript(args) {
2418
- if (args.dataInjection) {
2419
- return buildCustomDataInjectionScript(args.dataInjection);
2420
- }
2421
- return buildDataInjectionScript({
2422
- toolName: args.toolName,
2423
- input: args.input,
2424
- output: args.output,
2425
- structuredContent: args.structuredContent,
2426
- sizing: args.sizing,
2427
- displayMode: args.displayMode
2428
- });
2429
- }
2430
- function buildShell(content, config) {
2431
- const {
2432
- toolName,
2433
- csp,
2434
- withShell = true,
2435
- input,
2436
- output,
2437
- structuredContent,
2438
- includeBridge = true,
2439
- title,
2440
- sizing,
2441
- displayMode
2442
- } = config;
2443
- const { customShell, dataInjection } = config;
2444
- const dataScript = resolveDataInjectionScript({
2445
- dataInjection,
2446
- toolName,
2447
- input,
2448
- output,
2449
- structuredContent,
2450
- sizing,
2451
- displayMode
2452
- });
2453
- if (!withShell) {
2454
- const html2 = `${dataScript}
2455
- ${content}`;
2456
- return {
2457
- html: html2,
2458
- hash: simpleHash(html2),
2459
- size: Buffer.byteLength(html2, "utf-8")
2460
- };
2461
- }
2462
- if (customShell) {
2463
- return buildCustomShell(content, customShell, {
2464
- csp,
2465
- toolName,
2466
- input,
2467
- output,
2468
- structuredContent,
2469
- includeBridge,
2470
- title,
2471
- sizing,
2472
- displayMode,
2473
- dataInjection
2474
- });
2475
- }
2476
- const headParts = [
2477
- '<meta charset="UTF-8">',
2478
- '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
2479
- ];
2480
- if (title) {
2481
- headParts.push(`<title>${escapeHtmlForTag(title)}</title>`);
2482
- }
2483
- headParts.push(buildCSPMetaTag(csp));
2484
- headParts.push(dataScript);
2485
- const sizingStyle = buildSizingStyleTag(sizing);
2486
- if (sizingStyle) {
2487
- headParts.push(sizingStyle);
2488
- }
2489
- if (includeBridge) {
2490
- const bridgeScript = generateBridgeIIFE({ minify: true });
2491
- headParts.push(`<script>${bridgeScript}</script>`);
2492
- }
2493
- const html = `<!DOCTYPE html>
1253
+ </script>`}function buildCustomDataInjectionScript(descriptor){if(descriptor.script!==void 0){return descriptor.script}if(descriptor.globalKey!==void 0){return`<script>window[${safeJsonForScript(descriptor.globalKey)}] = ${safeJsonForScript(descriptor.value??null)};</script>`}return""}function sanitizeCssValue(value){return value.replace(/[<>{};]/g,"").trim()}function toCssLength(value){return typeof value==="number"?`${value}px`:sanitizeCssValue(value)}function buildSizingStyleTag(sizing){if(!hasSizing(sizing))return"";const hasCssSizing=sizing.preferredHeight!==void 0||sizing.minHeight!==void 0||sizing.maxHeight!==void 0||sizing.aspectRatio!==void 0;if(!hasCssSizing)return"";const rootRules=[];const docRules=["margin: 0;"];if(sizing.preferredHeight!==void 0){const h=toCssLength(sizing.preferredHeight);docRules.push(`height: ${h};`);rootRules.push(`min-height: ${h};`)}if(sizing.minHeight!==void 0){const mh=toCssLength(sizing.minHeight);docRules.push(`min-height: ${mh};`);rootRules.push(`min-height: ${mh};`)}if(sizing.maxHeight!==void 0){const mx=toCssLength(sizing.maxHeight);docRules.push(`max-height: ${mx};`);rootRules.push(`max-height: ${mx};`)}if(sizing.aspectRatio!==void 0){const ar=typeof sizing.aspectRatio==="number"?String(sizing.aspectRatio):sanitizeCssValue(sizing.aspectRatio);if(ar)rootRules.push(`aspect-ratio: ${ar};`)}const parts=[`html, body { ${docRules.join(" ")} }`];if(rootRules.length>0){parts.push(`#root { ${rootRules.join(" ")} }`)}return`<style>${parts.join("\n")}</style>`}function resolveDataInjectionScript(args){if(args.dataInjection){return buildCustomDataInjectionScript(args.dataInjection)}return buildDataInjectionScript({toolName:args.toolName,input:args.input,output:args.output,structuredContent:args.structuredContent,sizing:args.sizing,displayMode:args.displayMode})}function buildShell(content,config){const{toolName,csp,withShell=true,input,output,structuredContent,includeBridge=true,title,sizing,displayMode}=config;const{customShell,dataInjection}=config;const dataScript=resolveDataInjectionScript({dataInjection,toolName,input,output,structuredContent,sizing,displayMode});if(!withShell){const html2=`${dataScript}
1254
+ ${content}`;return{html:html2,hash:simpleHash(html2),size:Buffer.byteLength(html2,"utf-8")}}if(customShell){return buildCustomShell(content,customShell,{csp,toolName,input,output,structuredContent,includeBridge,title,sizing,displayMode,dataInjection})}const headParts=['<meta charset="UTF-8">','<meta name="viewport" content="width=device-width, initial-scale=1.0">'];if(title){headParts.push(`<title>${escapeHtmlForTag(title)}</title>`)}headParts.push(buildCSPMetaTag(csp));headParts.push(dataScript);const sizingStyle=buildSizingStyleTag(sizing);if(sizingStyle){headParts.push(sizingStyle)}if(includeBridge){const bridgeScript=generateBridgeIIFE({minify:true});headParts.push(`<script>${bridgeScript}</script>`)}const html=`<!DOCTYPE html>
2494
1255
  <html lang="en">
2495
1256
  <head>
2496
- ${headParts.map((p) => ` ${p}`).join("\n")}
1257
+ ${headParts.map(p=>` ${p}`).join("\n")}
2497
1258
  </head>
2498
1259
  <body>
2499
1260
  ${content}
2500
1261
  </body>
2501
- </html>`;
2502
- return {
2503
- html,
2504
- hash: simpleHash(html),
2505
- size: Buffer.byteLength(html, "utf-8")
2506
- };
2507
- }
2508
- function buildCustomShell(content, customShell, ctx) {
2509
- let template;
2510
- if (typeof customShell === "string") {
2511
- const validation = validateShellTemplate(customShell);
2512
- if (!validation.valid) {
2513
- throw new Error(
2514
- `Custom shell template is missing required placeholder(s): ${validation.missingRequired.map((n) => `{{${n}}}`).join(", ")}`
2515
- );
2516
- }
2517
- template = customShell;
2518
- } else {
2519
- template = customShell.template;
2520
- }
2521
- const cspTag = buildCSPMetaTag(ctx.csp);
2522
- const dataScript = resolveDataInjectionScript({
2523
- dataInjection: ctx.dataInjection,
2524
- toolName: ctx.toolName,
2525
- input: ctx.input,
2526
- output: ctx.output,
2527
- structuredContent: ctx.structuredContent,
2528
- sizing: ctx.sizing,
2529
- displayMode: ctx.displayMode
2530
- });
2531
- const sizingStyle = buildSizingStyleTag(ctx.sizing);
2532
- const dataWithSizing = sizingStyle ? `${dataScript}
2533
- ${sizingStyle}` : dataScript;
2534
- let bridgeHtml = "";
2535
- if (ctx.includeBridge) {
2536
- const bridgeScript = generateBridgeIIFE({ minify: true });
2537
- bridgeHtml = `<script>${bridgeScript}</script>`;
2538
- }
2539
- const html = applyShellTemplate(template, {
2540
- csp: cspTag,
2541
- data: dataWithSizing,
2542
- bridge: bridgeHtml,
2543
- content,
2544
- title: ctx.title ? escapeHtmlForTag(ctx.title) : ""
2545
- });
2546
- return {
2547
- html,
2548
- hash: simpleHash(html),
2549
- size: Buffer.byteLength(html, "utf-8")
2550
- };
2551
- }
2552
- function simpleHash(str) {
2553
- let hash = 0;
2554
- for (let i = 0; i < str.length; i++) {
2555
- const char = str.charCodeAt(i);
2556
- hash = (hash << 5) - hash + char | 0;
2557
- }
2558
- return Math.abs(hash).toString(16).padStart(8, "0");
2559
- }
2560
- function escapeHtmlForTag(str) {
2561
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2562
- }
2563
-
2564
- // libs/uipack/src/component/renderer.ts
2565
- var DEFAULT_WIDGET_MOUNT = {
2566
- moduleSpecifier: "@frontmcp/ui/react",
2567
- wrapperImportName: "McpBridgeProvider"
2568
- };
2569
- function renderComponent(config, shellConfig) {
2570
- const resolver = shellConfig.resolver ?? createEsmShResolver();
2571
- const resolved = resolveUISource(config.source, {
2572
- resolver,
2573
- input: shellConfig.input,
2574
- output: shellConfig.output,
2575
- inlineReact: config.inlineReact === true,
2576
- transformOnly: config.transformOnly === true
2577
- });
2578
- const mergedShellConfig = {
2579
- ...shellConfig,
2580
- withShell: config.withShell ?? shellConfig.withShell,
2581
- includeBridge: config.includeBridge ?? shellConfig.includeBridge,
2582
- customShell: config.customShell ?? shellConfig.customShell
2583
- };
2584
- if (resolved.mode === "inline") {
2585
- return buildShell(resolved.html ?? "", mergedShellConfig);
2586
- }
2587
- const content = buildModuleContent(resolved, resolver, config.props, shellConfig.mount);
2588
- return buildShell(content, mergedShellConfig);
2589
- }
2590
- function buildModuleContent(resolved, resolver, propsMapping, mount = DEFAULT_WIDGET_MOUNT) {
2591
- const parts = [];
2592
- if (resolved.code && resolved.bundled) {
2593
- const importEntries = {};
2594
- for (const spec of resolved.imports || []) {
2595
- const depResolved = resolver.resolve(spec);
2596
- if (depResolved) {
2597
- importEntries[spec] = depResolved;
2598
- }
2599
- }
2600
- if (Object.keys(importEntries).length > 0) {
2601
- const importMap = createImportMapFromResolved(importEntries);
2602
- parts.push(generateImportMapScriptTag(importMap));
2603
- }
2604
- parts.push('<div id="root"></div>');
2605
- parts.push(`<script type="module">
1262
+ </html>`;return{html,hash:simpleHash(html),size:Buffer.byteLength(html,"utf-8")}}function buildCustomShell(content,customShell,ctx){let template;if(typeof customShell==="string"){const validation=validateShellTemplate(customShell);if(!validation.valid){throw new Error(`Custom shell template is missing required placeholder(s): ${validation.missingRequired.map(n=>`{{${n}}}`).join(", ")}`)}template=customShell}else{template=customShell.template}const cspTag=buildCSPMetaTag(ctx.csp);const dataScript=resolveDataInjectionScript({dataInjection:ctx.dataInjection,toolName:ctx.toolName,input:ctx.input,output:ctx.output,structuredContent:ctx.structuredContent,sizing:ctx.sizing,displayMode:ctx.displayMode});const sizingStyle=buildSizingStyleTag(ctx.sizing);const dataWithSizing=sizingStyle?`${dataScript}
1263
+ ${sizingStyle}`:dataScript;let bridgeHtml="";if(ctx.includeBridge){const bridgeScript=generateBridgeIIFE({minify:true});bridgeHtml=`<script>${bridgeScript}</script>`}const html=applyShellTemplate(template,{csp:cspTag,data:dataWithSizing,bridge:bridgeHtml,content,title:ctx.title?escapeHtmlForTag(ctx.title):""});return{html,hash:simpleHash(html),size:Buffer.byteLength(html,"utf-8")}}function simpleHash(str){let hash=0;for(let i=0;i<str.length;i++){const char=str.charCodeAt(i);hash=(hash<<5)-hash+char|0}return Math.abs(hash).toString(16).padStart(8,"0")}function escapeHtmlForTag(str){return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var DEFAULT_WIDGET_MOUNT={moduleSpecifier:"@frontmcp/ui/react",wrapperImportName:"McpBridgeProvider"};function renderComponent(config,shellConfig){const resolver=shellConfig.resolver??createEsmShResolver();const resolved=resolveUISource(config.source,{resolver,input:shellConfig.input,output:shellConfig.output,inlineReact:config.inlineReact===true,transformOnly:config.transformOnly===true});const mergedShellConfig={...shellConfig,withShell:config.withShell??shellConfig.withShell,includeBridge:config.includeBridge??shellConfig.includeBridge,customShell:config.customShell??shellConfig.customShell};if(resolved.mode==="inline"){return buildShell(resolved.html??"",mergedShellConfig)}const content=buildModuleContent(resolved,resolver,config.props,shellConfig.mount);return buildShell(content,mergedShellConfig)}function buildModuleContent(resolved,resolver,propsMapping,mount=DEFAULT_WIDGET_MOUNT){const parts=[];if(resolved.code&&resolved.bundled){const importEntries={};for(const spec of resolved.imports||[]){const depResolved=resolver.resolve(spec);if(depResolved){importEntries[spec]=depResolved}}if(Object.keys(importEntries).length>0){const importMap=createImportMapFromResolved(importEntries);parts.push(generateImportMapScriptTag(importMap))}parts.push('<div id="root"></div>');parts.push(`<script type="module">
2606
1264
  ${resolved.code}
2607
- </script>`);
2608
- } else if (resolved.code) {
2609
- const importEntries = {};
2610
- const allSpecifiers = /* @__PURE__ */ new Set([
2611
- ...resolved.imports || [],
2612
- "react-dom/client",
2613
- // needed by mount script
2614
- mount.moduleSpecifier,
2615
- // mounter/provider package (e.g. @frontmcp/ui/react)
2616
- // React subpath entries needed by esm.sh externalized modules:
2617
- "react/jsx-runtime",
2618
- "react/jsx-dev-runtime"
2619
- ]);
2620
- if (mount === DEFAULT_WIDGET_MOUNT) {
2621
- allSpecifiers.add("react-dom/server");
2622
- allSpecifiers.add("react-dom/static");
2623
- }
2624
- const coreDeps = /* @__PURE__ */ new Set([
2625
- "react",
2626
- "react-dom",
2627
- "react-dom/client",
2628
- "react/jsx-runtime",
2629
- "react/jsx-dev-runtime",
2630
- "react-dom/server",
2631
- "react-dom/static"
2632
- ]);
2633
- for (const spec of allSpecifiers) {
2634
- const depResolved = resolver.resolve(spec);
2635
- if (depResolved) {
2636
- if (!coreDeps.has(spec) && depResolved.value?.includes("esm.sh")) {
2637
- importEntries[spec] = {
2638
- ...depResolved,
2639
- value: addExternalParam(depResolved.value, ["react", "react-dom"])
2640
- };
2641
- } else {
2642
- importEntries[spec] = depResolved;
2643
- }
2644
- }
2645
- }
2646
- if (importEntries["react-dom"] && !importEntries["react-dom/client"]) {
2647
- const rdc = resolver.resolve("react-dom/client");
2648
- if (rdc) importEntries["react-dom/client"] = rdc;
2649
- }
2650
- if (Object.keys(importEntries).length > 0) {
2651
- const importMap = createImportMapFromResolved(importEntries);
2652
- parts.push(generateImportMapScriptTag(importMap));
2653
- }
2654
- const mountNodeId = mount.mountNodeId ?? "root";
2655
- parts.push(`<div id="${mountNodeId}">${mount.mountNodeInnerHtml ?? ""}</div>`);
2656
- const mountCode = generateInlineMountCode(resolved.exportName, mount);
2657
- parts.push(`<script type="module">
1265
+ </script>`)}else if(resolved.code){const importEntries={};const allSpecifiers=new Set([...resolved.imports||[],"react-dom/client",mount.moduleSpecifier,"react/jsx-runtime","react/jsx-dev-runtime"]);if(mount===DEFAULT_WIDGET_MOUNT){allSpecifiers.add("react-dom/server");allSpecifiers.add("react-dom/static")}const coreDeps=new Set(["react","react-dom","react-dom/client","react/jsx-runtime","react/jsx-dev-runtime","react-dom/server","react-dom/static"]);for(const spec of allSpecifiers){const depResolved=resolver.resolve(spec);if(depResolved){if(!coreDeps.has(spec)&&depResolved.value?.includes("esm.sh")){importEntries[spec]={...depResolved,value:addExternalParam(depResolved.value,["react","react-dom"])}}else{importEntries[spec]=depResolved}}}if(importEntries["react-dom"]&&!importEntries["react-dom/client"]){const rdc=resolver.resolve("react-dom/client");if(rdc)importEntries["react-dom/client"]=rdc}if(Object.keys(importEntries).length>0){const importMap=createImportMapFromResolved(importEntries);parts.push(generateImportMapScriptTag(importMap))}const mountNodeId=mount.mountNodeId??"root";parts.push(`<div id="${mountNodeId}">${mount.mountNodeInnerHtml??""}</div>`);const mountCode=generateInlineMountCode(resolved.exportName,mount);parts.push(`<script type="module">
2658
1266
  ${resolved.code}
2659
1267
  ${mountCode}
2660
- </script>`);
2661
- } else {
2662
- const importEntries = {};
2663
- for (const dep of resolved.peerDependencies) {
2664
- const depResolved = resolver.resolve(dep);
2665
- if (depResolved) {
2666
- importEntries[dep] = depResolved;
2667
- }
2668
- }
2669
- if (importEntries["react-dom"]) {
2670
- const reactDomClient = resolver.resolve("react-dom/client");
2671
- if (reactDomClient) {
2672
- importEntries["react-dom/client"] = reactDomClient;
2673
- }
2674
- }
2675
- if (Object.keys(importEntries).length > 0) {
2676
- const importMap = createImportMapFromResolved(importEntries);
2677
- parts.push(generateImportMapScriptTag(importMap));
2678
- }
2679
- parts.push('<div id="root"></div>');
2680
- const mountScript = generateMountScript(resolved, propsMapping);
2681
- if (mountScript) {
2682
- parts.push(`<script type="module">
1268
+ </script>`)}else{const importEntries={};for(const dep of resolved.peerDependencies){const depResolved=resolver.resolve(dep);if(depResolved){importEntries[dep]=depResolved}}if(importEntries["react-dom"]){const reactDomClient=resolver.resolve("react-dom/client");if(reactDomClient){importEntries["react-dom/client"]=reactDomClient}}if(Object.keys(importEntries).length>0){const importMap=createImportMapFromResolved(importEntries);parts.push(generateImportMapScriptTag(importMap))}parts.push('<div id="root"></div>');const mountScript=generateMountScript(resolved,propsMapping);if(mountScript){parts.push(`<script type="module">
2683
1269
  ${mountScript}
2684
- </script>`);
2685
- }
2686
- }
2687
- return parts.join("\n");
2688
- }
2689
- function addExternalParam(url, externals) {
2690
- const sep = url.includes("?") ? "&" : "?";
2691
- return `${url}${sep}external=${externals.join(",")}`;
2692
- }
2693
- function generateInlineMountCode(componentName, mount) {
2694
- if (mount.generate) {
2695
- return mount.generate(componentName);
2696
- }
2697
- const wrapperName = mount.wrapperImportName ?? "McpBridgeProvider";
2698
- const wrapperAlias = `__${wrapperName}`;
2699
- const mountNodeId = mount.mountNodeId ?? "root";
2700
- return `
1270
+ </script>`)}}return parts.join("\n")}function addExternalParam(url,externals){const sep=url.includes("?")?"&":"?";return`${url}${sep}external=${externals.join(",")}`}function generateInlineMountCode(componentName,mount){if(mount.generate){return mount.generate(componentName)}const wrapperName=mount.wrapperImportName??"McpBridgeProvider";const wrapperAlias=`__${wrapperName}`;const mountNodeId=mount.mountNodeId??"root";return`
2701
1271
  // --- Mount ---
2702
1272
  import { createRoot as __createRoot } from 'react-dom/client';
2703
1273
  import { ${wrapperName} as ${wrapperAlias} } from '${mount.moduleSpecifier}';
@@ -2708,19 +1278,4 @@ if (__root) {
2708
1278
  React.createElement(${componentName})
2709
1279
  )
2710
1280
  );
2711
- }`;
2712
- }
2713
- // Annotate the CommonJS export names for ESM import in node:
2714
- 0 && (module.exports = {
2715
- FRONTMCP_META_KEY,
2716
- bundleFileSource,
2717
- extractDefaultExportName,
2718
- generateMountScript,
2719
- isFileSource,
2720
- isFunctionSource,
2721
- isImportSource,
2722
- isNpmSource,
2723
- renderComponent,
2724
- resolveUISource,
2725
- transpileReactSource
2726
- });
1281
+ }`}0&&(module.exports={FRONTMCP_META_KEY,bundleFileSource,extractDefaultExportName,generateMountScript,isFileSource,isFunctionSource,isImportSource,isNpmSource,renderComponent,resolveUISource,transpileReactSource});