@trops/dash-core 0.1.712 → 0.1.715

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.
@@ -0,0 +1,498 @@
1
+ 'use strict';
2
+
3
+ var require$$0 = require('fs');
4
+ var require$$1 = require('path');
5
+
6
+ function getDefaultExportFromCjs (x) {
7
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
8
+ }
9
+
10
+ /**
11
+ * toolPattern — wildcard MCP tool names.
12
+ *
13
+ * Some MCP servers name tools after the user's own data, e.g. Algolia's
14
+ * hosted server exposes one `algolia_search_<index>` tool per index the
15
+ * user added. A widget calls them with a template literal
16
+ * (`callTool(\`algolia_search_${selectedIndex}\`)`), so the real names
17
+ * aren't known until the server is connected.
18
+ *
19
+ * The scanner turns such a template into a pattern (`algolia_search_*`)
20
+ * and the gate treats `*` as "any characters". A pattern must keep some
21
+ * literal text — a bare `${toolName}` would grant every tool, so it is
22
+ * dropped and the call falls through to JIT consent instead.
23
+ */
24
+
25
+ const MIN_LITERAL_CHARS = 3;
26
+
27
+ function isToolPattern$1(name) {
28
+ return typeof name === "string" && name.includes("*");
29
+ }
30
+
31
+ /**
32
+ * `algolia_search_${selectedIndex}` → `algolia_search_*`.
33
+ * Returns the name unchanged when it has no `${…}`, or null when the
34
+ * template has too little literal text to be a safe pattern.
35
+ */
36
+ function toolPatternFromTemplate$1(raw) {
37
+ if (typeof raw !== "string") return null;
38
+ if (!raw.includes("${")) return raw;
39
+ const pattern = raw.replace(/\$\{[^}]*\}/g, "*").replace(/\*+/g, "*");
40
+ const literal = pattern.replace(/\*/g, "");
41
+ if (literal.length < MIN_LITERAL_CHARS || /[${}]/.test(literal)) return null;
42
+ return pattern;
43
+ }
44
+
45
+ function _patternRegex(pattern) {
46
+ const body = pattern
47
+ .split("*")
48
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
49
+ .join(".*");
50
+ return new RegExp("^" + body + "$");
51
+ }
52
+
53
+ /** True when `entry` (a tool name or pattern) covers `toolName`. */
54
+ function toolMatches(entry, toolName) {
55
+ if (typeof entry !== "string" || typeof toolName !== "string") return false;
56
+ if (entry === toolName) return true;
57
+ return isToolPattern$1(entry) && _patternRegex(entry).test(toolName);
58
+ }
59
+
60
+ /** True when any entry in `tools` covers `toolName`. */
61
+ function toolListAllows$1(tools, toolName) {
62
+ return Array.isArray(tools) && tools.some((t) => toolMatches(t, toolName));
63
+ }
64
+
65
+ var toolPattern = {
66
+ isToolPattern: isToolPattern$1,
67
+ toolPatternFromTemplate: toolPatternFromTemplate$1,
68
+ toolMatches,
69
+ toolListAllows: toolListAllows$1,
70
+ };
71
+
72
+ /**
73
+ * scanWidgetPackagePermissions
74
+ *
75
+ * Walks a widget package directory, statically extracts MCP usage
76
+ * (`useMcpProvider("type")` + `callTool("name", ...)`) from every
77
+ * source file, and returns the canonical `dash.permissions.mcp` block
78
+ * for embedding in the package's `package.json`.
79
+ *
80
+ * Used at three boundaries to keep declared permissions in sync with
81
+ * the actual code:
82
+ * - Widget publish flow (registry:publish-widget) — declarations
83
+ * ship with the package.
84
+ * - Widget install flow (installFromLocalPath) — declarations are
85
+ * re-derived for already-published packages whose authors didn't
86
+ * run the scanner, AND for new versions that updated their tool
87
+ * set without updating the manifest.
88
+ * - AI builder (widget:ai-build) — same scanner, single source of
89
+ * truth.
90
+ *
91
+ * MERGE policy: scanner output is additive. Hand-authored entries in
92
+ * `package.json.dash.permissions.mcp` are preserved; scanner-found
93
+ * entries the human missed are appended. Idempotent — repeated runs
94
+ * produce the same package.json (assuming source code unchanged).
95
+ *
96
+ * Limitations (acceptable, documented):
97
+ * - Single-string regex scan. Variable-indirected calls like
98
+ * `callTool(toolName, ...)` are skipped — runtime gate is the
99
+ * safety net.
100
+ * - Comments are stripped (line `//` only) so commented-out
101
+ * examples don't pollute the declaration.
102
+ * - Walks `widgets/`, `src/`, and the package root for `.js`,
103
+ * `.jsx`, `.ts`, `.tsx` files. Skips `node_modules/` and `dist/`.
104
+ */
105
+
106
+ const fs = require$$0;
107
+ const path = require$$1;
108
+ const {
109
+ toolPatternFromTemplate,
110
+ isToolPattern,
111
+ toolListAllows,
112
+ } = toolPattern;
113
+
114
+ const SOURCE_EXTS = new Set([".js", ".jsx", ".ts", ".tsx"]);
115
+ const SKIP_DIRS = new Set([
116
+ "node_modules",
117
+ "dist",
118
+ "build",
119
+ ".git",
120
+ "__tests__",
121
+ "__mocks__",
122
+ ]);
123
+
124
+ function _stripLineComments(code) {
125
+ return code.replace(/\/\/[^\n]*/g, "");
126
+ }
127
+
128
+ function _captureAll(code, pattern) {
129
+ const out = [];
130
+ for (const match of code.matchAll(pattern)) {
131
+ out.push(match[1]);
132
+ }
133
+ return out;
134
+ }
135
+
136
+ /**
137
+ * Scan a single file's contents and return any detected MCP usage.
138
+ * @param {string} code
139
+ * @returns {{providers: string[], tools: string[]}}
140
+ */
141
+ function scanFileForMcpUsage(code) {
142
+ if (typeof code !== "string" || !code) return { providers: [], tools: [] };
143
+ const stripped = _stripLineComments(code);
144
+ const providerPattern = /useMcpProvider\s*\(\s*["'`]([^"'`]+)["'`]/g;
145
+ // Group 2 is the literal; group 3 is set when the literal is followed by
146
+ // `.concat(` — the compiled form of a template (`"a_".concat(x)`).
147
+ const callPattern = /callTool\s*\(\s*(["'`])([^"'`]+)\1(\s*\.concat\s*\()?/g;
148
+ const tools = [];
149
+ for (const m of stripped.matchAll(callPattern)) {
150
+ // Template names (`algolia_search_${index}`) become wildcard patterns
151
+ // (`algolia_search_*`); ones too vague to pattern are dropped.
152
+ const raw = m[3] ? m[2] + "${}" : m[2];
153
+ const tool = toolPatternFromTemplate(raw);
154
+ if (tool) tools.push(tool);
155
+ }
156
+ return {
157
+ providers: Array.from(new Set(_captureAll(stripped, providerPattern))),
158
+ tools: Array.from(new Set(tools)),
159
+ };
160
+ }
161
+
162
+ function _walkSourceFiles(dir) {
163
+ const out = [];
164
+ if (!fs.existsSync(dir)) return out;
165
+ let entries;
166
+ try {
167
+ entries = fs.readdirSync(dir, { withFileTypes: true });
168
+ } catch (_) {
169
+ return out;
170
+ }
171
+ for (const entry of entries) {
172
+ if (entry.isDirectory()) {
173
+ if (SKIP_DIRS.has(entry.name)) continue;
174
+ out.push(..._walkSourceFiles(path.join(dir, entry.name)));
175
+ } else if (entry.isFile()) {
176
+ const ext = path.extname(entry.name);
177
+ if (SOURCE_EXTS.has(ext)) out.push(path.join(dir, entry.name));
178
+ }
179
+ }
180
+ return out;
181
+ }
182
+
183
+ /**
184
+ * Locate the package's `widgets/` directory and enumerate every
185
+ * `<Name>.js` paired with a `<Name>.dash.js` config. That pair is the
186
+ * canonical widget shape across the repo (see
187
+ * `widgetCompiler.findWidgetsDir`). Returns
188
+ * [{componentName, componentFilePath}].
189
+ *
190
+ * Files without a sibling `.dash.js` (utils, helpers, contexts) are
191
+ * skipped — they're not widgets, so attributing their MCP usage to a
192
+ * specific component is ambiguous.
193
+ */
194
+ function _findComponentFiles(packageDir) {
195
+ const candidates = [
196
+ path.join(packageDir, "widgets"),
197
+ path.join(packageDir, "src", "widgets"),
198
+ ];
199
+ const out = [];
200
+ for (const widgetsDir of candidates) {
201
+ if (!fs.existsSync(widgetsDir)) continue;
202
+ let entries;
203
+ try {
204
+ entries = fs.readdirSync(widgetsDir, { withFileTypes: true });
205
+ } catch (_) {
206
+ continue;
207
+ }
208
+ for (const entry of entries) {
209
+ if (!entry.isFile()) continue;
210
+ const m = entry.name.match(/^(.+)\.dash\.(?:js|jsx|ts|tsx)$/);
211
+ if (!m) continue;
212
+ const componentName = m[1];
213
+ // Prefer .js, then .jsx, .ts, .tsx — first-match wins.
214
+ for (const ext of [".js", ".jsx", ".ts", ".tsx"]) {
215
+ const componentFilePath = path.join(
216
+ widgetsDir,
217
+ `${componentName}${ext}`,
218
+ );
219
+ if (fs.existsSync(componentFilePath)) {
220
+ out.push({ componentName, componentFilePath });
221
+ break;
222
+ }
223
+ }
224
+ }
225
+ }
226
+ return out;
227
+ }
228
+
229
+ /**
230
+ * Walk packageDir, scan every source file, return the canonical
231
+ * `dash.permissions.mcp` block. Returns `{}` when no MCP usage found.
232
+ *
233
+ * Per-file pairing — providers and tools are paired at the source-file
234
+ * level, not unioned across the whole package. The vast majority of
235
+ * widget source files use a single `useMcpProvider("type")` hook and
236
+ * call its tools in the same file; pairing per file produces the
237
+ * correct provider→tools mapping for that case.
238
+ *
239
+ * Multi-widget packages (one package shipping N widgets, each with a
240
+ * different provider) used to be miscompiled by the old whole-package
241
+ * union: every provider in the package got credit for every tool any
242
+ * sibling widget called. The result was a manifest where, e.g., the
243
+ * `slack` server claimed `list_pull_requests` and `list_directory`
244
+ * tools simply because the same package also shipped a GitHub widget
245
+ * and a Filesystem widget. Per-file pairing eliminates that
246
+ * cross-pollination because each file's tools attach only to that
247
+ * file's providers.
248
+ *
249
+ * Files containing multiple providers (a widget that orchestrates two
250
+ * MCP servers in the same component) attribute their tools to each
251
+ * provider in that file — an acceptable over-grant within the single
252
+ * widget's own scope, and a rare-enough case that we don't try to
253
+ * parse expression scoping. Tools called in files with NO provider
254
+ * hook (e.g. a helper module called from a parent widget) are ignored
255
+ * — a runtime hint without static evidence of which provider it
256
+ * targets falls through to the gate's JIT consent.
257
+ */
258
+ function scanWidgetPackagePermissions(packageDir) {
259
+ if (typeof packageDir !== "string" || !fs.existsSync(packageDir)) return {};
260
+
261
+ const providerToTools = new Map();
262
+ for (const filePath of _walkSourceFiles(packageDir)) {
263
+ let code;
264
+ try {
265
+ code = fs.readFileSync(filePath, "utf8");
266
+ } catch (_) {
267
+ continue;
268
+ }
269
+ const { providers, tools } = scanFileForMcpUsage(code);
270
+ // No provider in this file → tools have no statically-known
271
+ // server to attach to. Skip rather than cross-pollinate.
272
+ if (providers.length === 0) continue;
273
+ // No tools in this file → still register the provider with an
274
+ // empty set so the manifest knows the widget declares this
275
+ // server. (Edge case: helper file that mounts useMcpProvider but
276
+ // calls callTool via an indirection we can't statically read.)
277
+ for (const p of providers) {
278
+ if (!providerToTools.has(p)) providerToTools.set(p, new Set());
279
+ const bucket = providerToTools.get(p);
280
+ for (const t of tools) bucket.add(t);
281
+ }
282
+ }
283
+
284
+ // Drop providers that ended up with no tools across the whole
285
+ // package — declaring a server with an empty tool list is
286
+ // misleading downstream (the Permissions panel renders an empty
287
+ // section, the gate treats it as "all tools require JIT"). The
288
+ // runtime gate is the safety net for tools we couldn't statically
289
+ // pair.
290
+ const out = {};
291
+ for (const [provider, toolSet] of providerToTools.entries()) {
292
+ if (toolSet.size === 0) continue;
293
+ out[provider] = { tools: Array.from(toolSet).sort() };
294
+ }
295
+ return out;
296
+ }
297
+
298
+ /**
299
+ * Per-component scanner. Walks each `widgets/<Name>.js` paired with
300
+ * `widgets/<Name>.dash.js` and produces a map
301
+ * { [componentName]: { [server]: { tools: [...] } } }
302
+ *
303
+ * Each component's entry contains ONLY the providers + tools its own
304
+ * file uses. Sibling widgets in the same package don't bleed into
305
+ * each other — the bug the package-level `mcp` block carries by
306
+ * design (one shared block for the whole package) is closed here at
307
+ * the widget granularity.
308
+ *
309
+ * Used by `widgetPermissions.getWidgetMcpPermissions(scopedWidgetId)`
310
+ * to answer "what does THIS specific widget declare" instead of
311
+ * "what does the WHOLE package declare", which is what fixes:
312
+ * - Permissions panel showing every sibling's declarations under
313
+ * every widget
314
+ * - JIT consent's sibling-fanout writing grants to widgets that
315
+ * don't actually use the granted tool
316
+ *
317
+ * Returns `{}` when no component file declares any MCP usage.
318
+ */
319
+ function scanWidgetPackagePermissionsByComponent(packageDir) {
320
+ if (typeof packageDir !== "string" || !fs.existsSync(packageDir)) return {};
321
+ const out = {};
322
+ for (const { componentName, componentFilePath } of _findComponentFiles(
323
+ packageDir,
324
+ )) {
325
+ let code;
326
+ try {
327
+ code = fs.readFileSync(componentFilePath, "utf8");
328
+ } catch (_) {
329
+ continue;
330
+ }
331
+ const { providers, tools } = scanFileForMcpUsage(code);
332
+ if (providers.length === 0) continue;
333
+ // Pair this file's providers with this file's tools — same
334
+ // per-file logic as `scanWidgetPackagePermissions`, scoped to
335
+ // a single widget's component file.
336
+ const servers = {};
337
+ for (const provider of providers) {
338
+ const sorted = Array.from(new Set(tools)).sort();
339
+ if (sorted.length === 0) continue;
340
+ servers[provider] = { tools: sorted };
341
+ }
342
+ if (Object.keys(servers).length > 0) {
343
+ out[componentName] = { servers };
344
+ }
345
+ }
346
+ return out;
347
+ }
348
+
349
+ /**
350
+ * Merge scanner output with any hand-authored block. Additive:
351
+ * - Servers in `human` are kept as-is.
352
+ * - Servers in `scanned` not in `human` are added.
353
+ * - When the same server is in both, the union of `tools` arrays is
354
+ * written, preserving any read/write paths the human declared.
355
+ */
356
+ function mergePermissions(human, scanned) {
357
+ const out = {};
358
+ // Older scans wrote raw template names (`x_${y}`), which never match a
359
+ // real tool. Drop them; the scanner now emits a pattern instead.
360
+ const real = (tools) => tools.filter((t) => !String(t).includes("${"));
361
+ // Start with human entries (preserves their shape including paths).
362
+ if (human && typeof human === "object") {
363
+ for (const [name, perms] of Object.entries(human)) {
364
+ out[name] = { ...perms };
365
+ if (Array.isArray(perms.tools)) out[name].tools = real(perms.tools);
366
+ }
367
+ }
368
+ if (scanned && typeof scanned === "object") {
369
+ for (const [name, perms] of Object.entries(scanned)) {
370
+ if (!out[name]) {
371
+ out[name] = { tools: [...(perms.tools || [])] };
372
+ } else {
373
+ const existing = new Set(out[name].tools || []);
374
+ for (const t of perms.tools || []) existing.add(t);
375
+ // Drop plain names a scanned wildcard already covers, e.g. the
376
+ // "algolia_search_" older scans read from compiled bundles.
377
+ const wildcards = (perms.tools || []).filter(isToolPattern);
378
+ out[name].tools = Array.from(existing)
379
+ .filter((t) => isToolPattern(t) || !toolListAllows(wildcards, t))
380
+ .sort();
381
+ }
382
+ }
383
+ }
384
+ return out;
385
+ }
386
+
387
+ /**
388
+ * Apply the scanner's findings to `package.json` in `packageDir` —
389
+ * read, merge with any existing manifest, write back. Returns the
390
+ * resulting package-level `mcp` block (or null if no package.json AND
391
+ * no usage to write).
392
+ *
393
+ * Writes BOTH blocks:
394
+ * - `dash.permissions.mcp` — package-level union (back-compat with
395
+ * the gate's pre-per-component lookup path)
396
+ * - `dash.permissions.mcpByComponent` — per-widget breakdown so the
397
+ * Permissions panel and JIT-consent sibling fanout can answer
398
+ * "which specific widgets declare this tool" without cross-
399
+ * contaminating siblings
400
+ *
401
+ * The per-component block is fully scanner-derived (no hand-merge) —
402
+ * editing it by hand is unsupported. Package-level `mcp` continues
403
+ * to honor hand-authored entries.
404
+ */
405
+ function applyScanToPackageJson(packageDir) {
406
+ const pkgPath = path.join(packageDir, "package.json");
407
+ let existing = {};
408
+ if (fs.existsSync(pkgPath)) {
409
+ try {
410
+ existing = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
411
+ } catch (_) {
412
+ existing = {};
413
+ }
414
+ }
415
+ const scanned = scanWidgetPackagePermissions(packageDir);
416
+ const human = existing.dash?.permissions?.mcp || null;
417
+ const merged = mergePermissions(human, scanned);
418
+ const byComponent = scanWidgetPackagePermissionsByComponent(packageDir);
419
+ // Existing stale `mcpByComponent` from a prior scan must be dropped
420
+ // when this run finds no qualifying components — otherwise leftover
421
+ // entries for deleted widgets keep applying permissions the user
422
+ // didn't actually re-approve. Treat "has existing block but new
423
+ // scan empty" as a write trigger (with the side effect of removing
424
+ // the block via the delete below).
425
+ const hadByComponent =
426
+ !!existing.dash?.permissions?.mcpByComponent &&
427
+ typeof existing.dash.permissions.mcpByComponent === "object" &&
428
+ Object.keys(existing.dash.permissions.mcpByComponent).length > 0;
429
+ if (
430
+ Object.keys(merged).length === 0 &&
431
+ Object.keys(byComponent).length === 0 &&
432
+ !hadByComponent
433
+ ) {
434
+ // Nothing to write. Don't churn the file.
435
+ return null;
436
+ }
437
+ const nextPermissions = {
438
+ ...((existing.dash || {}).permissions || {}),
439
+ };
440
+ if (Object.keys(merged).length > 0) nextPermissions.mcp = merged;
441
+ if (Object.keys(byComponent).length > 0) {
442
+ nextPermissions.mcpByComponent = byComponent;
443
+ } else {
444
+ // Drop a stale `mcpByComponent` block when re-scanning finds no
445
+ // qualifying component files. Prevents leftover entries from a
446
+ // prior install lingering after the user deletes a widget.
447
+ delete nextPermissions.mcpByComponent;
448
+ }
449
+ const next = {
450
+ ...existing,
451
+ dash: {
452
+ ...(existing.dash || {}),
453
+ permissions: nextPermissions,
454
+ },
455
+ };
456
+ fs.writeFileSync(pkgPath, JSON.stringify(next, null, 2), "utf8");
457
+ return merged;
458
+ }
459
+
460
+ /**
461
+ * Run `applyScanToPackageJson` over a list of widget package paths.
462
+ * Used at registry boot to backfill `dash.permissions.mcp` for widgets
463
+ * installed before the publish/install scanner hooks existed (or that
464
+ * have since updated their tool set without re-publishing). Idempotent
465
+ * — additive merge means repeated boots produce no further writes.
466
+ *
467
+ * @param {string[]} packagePaths
468
+ * @returns {{scanned: number, modified: number, errors: Array<{path: string, error: string}>}}
469
+ */
470
+ function backfillPackagePermissions(packagePaths) {
471
+ const summary = { scanned: 0, modified: 0, errors: [] };
472
+ if (!Array.isArray(packagePaths)) return summary;
473
+ for (const pkgPath of packagePaths) {
474
+ if (typeof pkgPath !== "string" || !pkgPath) continue;
475
+ if (!fs.existsSync(pkgPath)) continue;
476
+ summary.scanned += 1;
477
+ try {
478
+ const merged = applyScanToPackageJson(pkgPath);
479
+ if (merged) summary.modified += 1;
480
+ } catch (e) {
481
+ summary.errors.push({ path: pkgPath, error: e.message });
482
+ }
483
+ }
484
+ return summary;
485
+ }
486
+
487
+ var scanWidgetPackagePermissions_1 = {
488
+ scanFileForMcpUsage,
489
+ scanWidgetPackagePermissions,
490
+ scanWidgetPackagePermissionsByComponent,
491
+ mergePermissions,
492
+ applyScanToPackageJson,
493
+ backfillPackagePermissions,
494
+ };
495
+
496
+ var scanWidgetPackagePermissions$1 = /*@__PURE__*/getDefaultExportFromCjs(scanWidgetPackagePermissions_1);
497
+
498
+ module.exports = scanWidgetPackagePermissions$1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trops/dash-core",
3
- "version": "0.1.712",
3
+ "version": "0.1.715",
4
4
  "description": "Core framework for Dash dashboard applications",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
@@ -11,6 +11,9 @@
11
11
  },
12
12
  "./electron": {
13
13
  "require": "./dist/electron/index.js"
14
+ },
15
+ "./scanner": {
16
+ "require": "./dist/scanner/index.js"
14
17
  }
15
18
  },
16
19
  "files": [