@thready-web/dsh-bot-plugin 0.1.0-beta.11 → 0.1.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +20 -3
  2. package/dist/approvals.js +19 -1
  3. package/dist/canvas-compose.js +73 -0
  4. package/dist/canvas-http.js +124 -0
  5. package/dist/canvas-inspector.js +350 -0
  6. package/dist/canvas-store.js +227 -6
  7. package/dist/canvas-tools.js +199 -30
  8. package/dist/card-log.js +216 -0
  9. package/dist/context.js +5 -3
  10. package/dist/deleting.js +54 -0
  11. package/dist/desk-ledger.js +18 -0
  12. package/dist/desk.js +30 -5
  13. package/dist/http-plugin.js +2 -1
  14. package/dist/http.js +200 -4
  15. package/dist/inbox.js +24 -2
  16. package/dist/index.js +65 -13
  17. package/dist/questions.js +10 -0
  18. package/dist/runtime-registry.js +20 -0
  19. package/dist/session-delete-job.js +77 -0
  20. package/dist/session-files.js +33 -1
  21. package/dist/session-wipe.js +204 -0
  22. package/dist/store.js +46 -3
  23. package/dist/triggers.js +8 -0
  24. package/dist/work-admit.js +9 -20
  25. package/dist/work-child.js +27 -10
  26. package/dist/work-ledger.js +5 -1
  27. package/dist/work-mock.js +10 -0
  28. package/dist/work-tickets.js +5 -3
  29. package/dist/work-tools.js +11 -9
  30. package/dist/work-worker.js +240 -6
  31. package/dist/worker-handles.js +33 -0
  32. package/dist/workspace-files.js +98 -17
  33. package/package.json +6 -3
  34. package/public/assets/{SourceEditor-uu0G7jsM.js → SourceEditor-BjtoMvcX.js} +3 -3
  35. package/public/assets/{cssMode-C5DAFF5H.js → cssMode--96PQtWh.js} +1 -1
  36. package/public/assets/{freemarker2-DExNwSiZ.js → freemarker2-Bz-HlISL.js} +1 -1
  37. package/public/assets/{handlebars-BK7YAvpQ.js → handlebars-D9ScJ8AM.js} +1 -1
  38. package/public/assets/{html-CdDm_zae.js → html-Czc0jojJ.js} +1 -1
  39. package/public/assets/{htmlMode-CLdn9oa1.js → htmlMode-CCww5Z1w.js} +1 -1
  40. package/public/assets/index-DRCgKxWk.css +1 -0
  41. package/public/assets/index-ztUdW074.js +72 -0
  42. package/public/assets/{javascript-mLl83_3W.js → javascript-B-yRZSiz.js} +1 -1
  43. package/public/assets/{jsonMode-B1-bihFd.js → jsonMode-ASWsY833.js} +1 -1
  44. package/public/assets/{liquid-Cv8m0HUb.js → liquid-BGoox2vJ.js} +1 -1
  45. package/public/assets/{mdx-Q12b91rL.js → mdx-DHgvnl_U.js} +1 -1
  46. package/public/assets/{python-Kda811W0.js → python-BJvVD30_.js} +1 -1
  47. package/public/assets/{razor-CRuCpdOW.js → razor-0PwR35mu.js} +1 -1
  48. package/public/assets/{tsMode-BGHcz-M3.js → tsMode-3ETp8Gdh.js} +1 -1
  49. package/public/assets/{typescript-Db1e0DCT.js → typescript-BT0iTK6K.js} +1 -1
  50. package/public/assets/{xml-H3zzFmnd.js → xml-BTaNc_uT.js} +1 -1
  51. package/public/assets/{yaml-BQrKvmTF.js → yaml-Dr7LW3tK.js} +1 -1
  52. package/public/index.html +2 -2
  53. package/skills/ui/ui-design/SKILL.md +11 -5
  54. package/public/assets/index-BB-QDSf2.css +0 -1
  55. package/public/assets/index-CsX-_qbo.js +0 -62
package/README.md CHANGED
@@ -83,7 +83,7 @@ Parked `needs_user` tickets still count toward the combined unfinished cap (`slo
83
83
 
84
84
  Workers share the owner's workspace. There is no filesystem isolation; briefings should state file boundaries, or dependent work should stay serial.
85
85
 
86
- Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. The host sandbox stays `workspace-write` with the existing approval policy. This does not mount the web preset, add writable roots, or switch the sandbox to `danger-full-access`. A reserved start that does not create a worker within `min(ticket wallMs, 10m)` fails with `reserve-wall` and frees the slot; a late `createChild` is cancelled instead of attached.
86
+ Workers use the `foundations-files` preset: official file tools plus official `@deepseek-ai/dsh-tool-bash` and `@deepseek-ai/dsh-tool-jobs`. A canvas worker uses `foundations-canvas` instead, which mounts the file tools with `write` and `edit` disabled and does not mount bash or jobs. Preview bytes go through `canvas_write`, not the workspace. The host sandbox stays `workspace-write` with the existing approval policy. This does not mount the web preset, add writable roots, or switch the sandbox to `danger-full-access`. A reserved start that does not create a worker within `min(ticket wallMs, 10m)` fails with `reserve-wall` and frees the slot; a late `createChild` is cancelled instead of attached.
87
87
 
88
88
  Runnable examples (any one of these is enough; `config.work` wins over the environment):
89
89
 
@@ -117,7 +117,7 @@ A granted worker token/runtime cap pauses admission at the official asynchronous
117
117
 
118
118
  The ticket retains its attempt, fencing token and child session. `budget_json.quota` durably records cumulative committed `usage.totalTokens`, deduplication sequence, active elapsed time, and requested/waiting phase. Active time includes finishing in-flight work until the safe boundary; suspended-boundary waiting time is excluded. Waiting is exempt from lease/enqueue expiry and has no hard-wall failure timer. It retains a worker slot to preserve capacity accounting; the main bot is not in this worker gate or slot pool and can always grant, deny or cancel. Explicit cancellation releases the slot normally.
119
119
 
120
- A grant adds amounts, never resets usage, and must exceed both current token usage and active time. An insufficient grant leaves the gate closed without another noisy extension event; its response includes usage, required totals, and the minimum additional amounts. One slice is 1,000,000 tokens and 30 minutes. The first dispatch uses that slice, and every later grant adds at least another slice. There is no cumulative ceiling and no limit on how many times a ticket can be extended. A refusal from the main session is ignored: another full slice is granted instead.
120
+ A grant adds amounts, never resets usage, and must exceed both current token usage and active time. An insufficient grant leaves the gate closed without another noisy extension event; its response includes usage, required totals, and the minimum additional amounts. One slice is 2,000,000 tokens and 60 minutes. Every dispatch starts on that slice. A budget passed with the dispatch is ignored. Every later grant adds at least another slice. There is no cumulative ceiling and no limit on how many times a ticket can be extended. A refusal from the main session is ignored: another full slice is granted instead.
121
121
 
122
122
  Budget requests are urgent next-turn inbox notices, bypassing stale notice/user/delivery admission barriers without steering or interrupting the main turn. Admission is single-flight per owner and rechecks grant/cancellation races before persisting a notice. Ordinary progress retains its existing admission policy. The workbench labels suspended workers “Waiting for budget”.
123
123
 
@@ -127,6 +127,23 @@ A process restart cannot preserve an in-memory DSH turn: the durable wait surviv
127
127
 
128
128
  Workbench sessions start in `THREADY_SESSION_CWD` when set, otherwise in `<DSH_HOME>/workspace` (created on first use), never in `DSH_HOME` itself, which holds the owner token and profiles.
129
129
 
130
+ The file drawer's Home root is a directory you choose, separate from process `HOME`. Set an existing directory with the http plugin's `files.home` or with `THREADY_FILES_HOME` (config wins). Leave `HOME` and `DSH_HOME` unchanged. The home directory is rejected when it is missing, not a directory, `DSH_HOME`, anything inside `DSH_HOME`, `/`, or `/etc`. Symlinks are judged by their real path. An invalid explicit value is not replaced with process `HOME`. When neither value is set, process `HOME` is used only if it passes those checks.
131
+
132
+ A workspace that is a subdirectory of `DSH_HOME` stays readable. A workspace that is `DSH_HOME`, or that contains it, stays closed. The one exception is a session whose stored cwd is exactly `DSH_HOME`: the drawer shows the configured session workspace instead, and only when that path is itself a safe directory. The stored cwd, session id, and history are not rewritten. Any other overlapping cwd stays closed.
133
+
134
+ ```yaml
135
+ - insert:
136
+ - id: session-foundations-http
137
+ name: "@thready-web/dsh-bot-plugin/http"
138
+ config:
139
+ files:
140
+ home: /opt/dsh-bot/files
141
+ ```
142
+
143
+ ```bash
144
+ THREADY_FILES_HOME=/opt/dsh-bot/files
145
+ ```
146
+
130
147
  Generated raster previews can be embedded at `/dsh-bot/<project>/preview/<image>` or `/dsh-bot/<project>/artifacts/<image>`. These are deliberate artifact directories under that configured workspace, not a general file server or a per-session sharing boundary: authenticated workbench users can view their images. Only JPEG, PNG, GIF and WebP with matching signatures are served, with private/no-store caching. Dotfiles, traversal, symlink escapes, other workspace locations and active HTML/SVG are rejected. With no configured workspace this fallback is disabled. Relative Markdown image paths resolve under `/dsh-bot/`; existing absolute URLs remain unchanged.
131
148
 
132
149
  Markdown images use bounded, aspect-preserving thumbnails. Click to open a viewport-fit dialog, then choose Original size to scroll through screenshot details. Escape, the close button or the backdrop dismisses it, restoring focus and body scrolling. Linked images expose their link separately from the preview control. Preview and unavailable-state labels follow the English/Chinese UI catalog.
@@ -145,7 +162,7 @@ A visible connected view reconciles once on entry and every 60 seconds. Unsuppor
145
162
 
146
163
  The authorization drawer loads the provider directory only on demand, with a per-App single-flight 30-second cache, no browser storage or cross-App cache. Local authorization lifecycle changes and mutations invalidate it. An open drawer revalidates every 30 seconds and on background resume: native provider registration has no complete event hook, so these changes are eventually reconciled rather than falsely treated as push-complete. Dynamic prompts/notices remain on the compact channel even when the drawer is closed.
147
164
 
148
- DSH loads `dist/`. Rebuild after changing `src/`. Until `npm --prefix ui run build` has run, `/dsh-bot/` is 404.
165
+ DSH loads `dist/`. Rebuild after changing `src/`. The plugin build also writes `dist/canvas-inspector.js`; a published install reads that file and does not compile the inspector on startup. Until `npm --prefix ui run build` has run, `/dsh-bot/` is 404.
149
166
 
150
167
  Host integration needs Node `>= 24.9` and `DSH_BIN`:
151
168
 
package/dist/approvals.js CHANGED
@@ -42,7 +42,7 @@ function displayReasonOf(value) {
42
42
  }
43
43
  return display;
44
44
  }
45
- export function createApprovalAnswerer() {
45
+ export function createApprovalAnswerer(record) {
46
46
  const pending = new Set();
47
47
  const settled = [];
48
48
  let nextId = 1;
@@ -91,6 +91,13 @@ export function createApprovalAnswerer() {
91
91
  };
92
92
  entry.onAbort = onAbort;
93
93
  pending.add(entry);
94
+ record?.({
95
+ sessionId,
96
+ requestId: entry.requestId,
97
+ toolName,
98
+ reason: textOf(request.reason),
99
+ ...(callId === '' ? {} : { callId }),
100
+ });
94
101
  if (request.signal?.aborted) {
95
102
  onAbort();
96
103
  return;
@@ -120,6 +127,16 @@ export function createApprovalAnswerer() {
120
127
  entry.resolve(input.outcome);
121
128
  return { ok: true, path: 'approval', outcome: input.outcome, requestId: entry.requestId };
122
129
  }
130
+ function abandonSession(sessionId) {
131
+ for (const entry of [...pending]) {
132
+ if (entry.sessionId !== sessionId)
133
+ continue;
134
+ if (!detach(entry))
135
+ continue;
136
+ remember(entry, 'unavailable');
137
+ entry.resolve('unavailable');
138
+ }
139
+ }
123
140
  function snapshot(sessionId) {
124
141
  const open = [...pending]
125
142
  .filter(entry => !sessionId || entry.sessionId === sessionId)
@@ -152,6 +169,7 @@ export function createApprovalAnswerer() {
152
169
  listen,
153
170
  handle,
154
171
  submit,
172
+ abandonSession,
155
173
  snapshot,
156
174
  pendingCount() {
157
175
  return pending.size;
@@ -0,0 +1,73 @@
1
+ import { parseHTML } from 'linkedom';
2
+ const DROP = new Set(['script', 'iframe', 'object', 'embed', 'base', 'meta', 'svg', 'foreignobject']);
3
+ function isRelativeAsset(href) {
4
+ if (href === '' || href.length > 200)
5
+ return false;
6
+ if (/[\s\\]/.test(href) || href.includes('..'))
7
+ return false;
8
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//') || href.startsWith('/'))
9
+ return false;
10
+ return true;
11
+ }
12
+ function escapeAttr(value) {
13
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
14
+ }
15
+ /** Keep a head <style> from closing itself and becoming markup. */
16
+ function escapeStyle(css) {
17
+ return css.replace(/<\/(style)/gi, '<\\/$1');
18
+ }
19
+ function scrub(el) {
20
+ for (const child of Array.from(el.children)) {
21
+ const tag = child.tagName.toLowerCase();
22
+ if (DROP.has(tag)) {
23
+ child.remove();
24
+ continue;
25
+ }
26
+ for (const attr of Array.from(child.attributes)) {
27
+ const name = attr.name.toLowerCase();
28
+ const value = attr.value.trim();
29
+ if (name.startsWith('on') || name === 'srcdoc')
30
+ child.removeAttribute(attr.name);
31
+ else if ((name === 'href' || name === 'src' || name === 'action' || name === 'formaction') &&
32
+ /^(javascript:|data:|https?:|\/\/)/i.test(value))
33
+ child.removeAttribute(attr.name);
34
+ }
35
+ scrub(child);
36
+ }
37
+ }
38
+ /** Scriptless design plus the host inspector. CSP stays with the caller. */
39
+ export function composeInspect(html, options) {
40
+ const { document } = parseHTML(html);
41
+ const sheets = [];
42
+ for (const node of Array.from(document.querySelectorAll('link, style'))) {
43
+ if (document.body.contains(node))
44
+ continue;
45
+ if (node.tagName === 'STYLE') {
46
+ const media = node.getAttribute('media');
47
+ const mediaAttr = media && media.length <= 200 && !/[\r\n<>]/.test(media) ? ` media="${escapeAttr(media)}"` : '';
48
+ sheets.push(`<style${mediaAttr}>${escapeStyle(node.textContent ?? '')}</style>`);
49
+ continue;
50
+ }
51
+ const rel = (node.getAttribute('rel') ?? '').toLowerCase();
52
+ const href = (node.getAttribute('href') ?? '').trim();
53
+ if (!rel.split(/\s+/).includes('stylesheet') || !isRelativeAsset(href))
54
+ continue;
55
+ sheets.push(`<link rel="stylesheet" href="${escapeAttr(href)}">`);
56
+ }
57
+ scrub(document.body);
58
+ return `<!doctype html>
59
+ <html>
60
+ <head>
61
+ <meta charset="utf-8">
62
+ <base href="${escapeAttr(options.baseHref)}">
63
+ <meta name="dsh-inspect-nonce" content="${escapeAttr(options.nonce)}">
64
+ <meta name="dsh-parent-origin" content="${escapeAttr(options.parentOrigin)}">
65
+ ${options.page ? `<meta name="dsh-inspect-page" content="${escapeAttr(options.page)}">` : ''}
66
+ ${sheets.join('\n')}
67
+ </head>
68
+ <body>
69
+ ${document.body.innerHTML}
70
+ <script src="${escapeAttr(options.inspectorSrc)}"></script>
71
+ </body>
72
+ </html>`;
73
+ }
@@ -1,7 +1,11 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { composeInspect } from "./canvas-compose.js";
1
3
  import { asStoreFailure, toolError } from "./errors.js";
2
4
  import { CANVAS_MAX_JSON_BYTES, normalizeCanvasPath } from "./canvas-store.js";
3
5
  const API = '/session-foundations/api/canvas';
4
6
  const MEDIA = '/dsh-bot/canvas-media/';
7
+ const INSPECT = '/dsh-bot/canvas-inspect/';
8
+ const INSPECTOR = '/dsh-bot/canvas-inspector.js';
5
9
  const CANVAS_ID = /^cnv_[A-Za-z0-9_-]{16}$/;
6
10
  /**
7
11
  * Manual and test publish routes. They require the existing login gate.
@@ -246,3 +250,123 @@ function json(res, status, body) {
246
250
  });
247
251
  res.end(text);
248
252
  }
253
+ const NONCE = /^[A-Za-z0-9_-]{16,80}$/;
254
+ let inspectorCode = null;
255
+ /** Token-only inspect document. The design stays scriptless; only the host inspector runs. */
256
+ export async function serveCanvasInspect(req, res, requestUrl, canvas) {
257
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
258
+ json(res, 405, toolError('VALIDATION', 'canvas inspect is read-only.'));
259
+ return;
260
+ }
261
+ const path = (requestUrl.split('?')[0] ?? '').replace(/\/+$/, '');
262
+ if (path === INSPECTOR) {
263
+ try {
264
+ const code = inspectorSource();
265
+ writeBody(res, req.method, 200, 'text/javascript; charset=utf-8', code, "default-src 'none'");
266
+ }
267
+ catch (error) {
268
+ json(res, 500, toolError('STORE_FAILURE', error instanceof Error ? error.message : 'inspector failed'));
269
+ }
270
+ return;
271
+ }
272
+ const parsed = parseCanvasInspect(requestUrl);
273
+ if (!parsed) {
274
+ json(res, 400, toolError('VALIDATION', 'canvas inspect path is not allowed.'));
275
+ return;
276
+ }
277
+ const nonce = new URL(requestUrl, 'http://127.0.0.1').searchParams.get('nonce');
278
+ if (!nonce || !NONCE.test(nonce)) {
279
+ json(res, 400, toolError('VALIDATION', 'canvas inspect nonce is required.'));
280
+ return;
281
+ }
282
+ if (!canvas) {
283
+ json(res, 404, toolError('NOT_FOUND', 'No such canvas file.'));
284
+ return;
285
+ }
286
+ const found = canvas.readMedia({ token: parsed.token, revision: parsed.revision, path: parsed.path });
287
+ if (found.ok === false) {
288
+ json(res, found.code === 'NOT_FOUND' ? 404 : found.code === 'VALIDATION' ? 400 : 401, found);
289
+ return;
290
+ }
291
+ if (found.type !== 'text/html') {
292
+ json(res, 404, toolError('NOT_FOUND', 'No such canvas file.'));
293
+ return;
294
+ }
295
+ const origin = requestOrigin(req);
296
+ if (origin === '') {
297
+ json(res, 400, toolError('VALIDATION', 'canvas inspect needs a host.'));
298
+ return;
299
+ }
300
+ const prefix = `${origin}${MEDIA}${parsed.token}/${parsed.revision}/`;
301
+ const html = composeInspect(found.bytes.toString('utf8'), {
302
+ baseHref: prefix,
303
+ nonce,
304
+ parentOrigin: origin,
305
+ inspectorSrc: INSPECTOR,
306
+ page: parsed.path,
307
+ });
308
+ writeBody(res, req.method, 200, 'text/html; charset=utf-8', html, inspectPolicy(origin, prefix));
309
+ }
310
+ export function parseCanvasInspect(requestUrl) {
311
+ const pathname = (requestUrl.split('?')[0] ?? '').replace(/\/+$/, '');
312
+ if (!pathname.startsWith(INSPECT))
313
+ return null;
314
+ if (pathname.includes('\\') || pathname.includes('%') || pathname.includes('\0'))
315
+ return null;
316
+ if (pathname.split('/').includes('..') || pathname.split('/').includes('.'))
317
+ return null;
318
+ const parts = pathname.slice(INSPECT.length).split('/');
319
+ if (parts.length < 2)
320
+ return null;
321
+ const [token, revision, ...rest] = parts;
322
+ if (!token || !/^[A-Za-z0-9_-]{20,128}$/.test(token))
323
+ return null;
324
+ if (!revision || !/^[1-9]\d{0,8}$/.test(revision))
325
+ return null;
326
+ const path = normalizeCanvasPath(rest.length === 0 ? 'index.html' : rest.join('/'));
327
+ if (!path || !path.endsWith('.html'))
328
+ return null;
329
+ return { token, revision: Number(revision), path };
330
+ }
331
+ function inspectPolicy(origin, prefix) {
332
+ return [
333
+ "default-src 'none'",
334
+ `img-src ${prefix}`,
335
+ `style-src ${prefix} 'unsafe-inline'`,
336
+ `font-src ${prefix}`,
337
+ `script-src ${origin}${INSPECTOR}`,
338
+ `base-uri ${prefix}`,
339
+ `frame-ancestors ${origin}`,
340
+ "form-action 'none'",
341
+ 'sandbox allow-scripts',
342
+ ].join('; ');
343
+ }
344
+ function writeBody(res, method, status, type, body, policy) {
345
+ res.writeHead(status, {
346
+ 'content-type': type,
347
+ 'content-length': Buffer.byteLength(body),
348
+ 'cache-control': 'private, no-store',
349
+ 'x-content-type-options': 'nosniff',
350
+ 'referrer-policy': 'no-referrer',
351
+ 'content-security-policy': policy,
352
+ });
353
+ res.end(method === 'HEAD' ? undefined : body);
354
+ }
355
+ function inspectorSource() {
356
+ if (inspectorCode != null)
357
+ return inspectorCode;
358
+ // dist/canvas-http.js reads the sibling bundle. Tests import src/ and use the same built file.
359
+ const candidates = [
360
+ new URL('./canvas-inspector.js', import.meta.url),
361
+ new URL('../dist/canvas-inspector.js', import.meta.url),
362
+ ];
363
+ for (const url of candidates) {
364
+ if (!existsSync(url))
365
+ continue;
366
+ inspectorCode = readFileSync(url, 'utf8');
367
+ if (inspectorCode === '')
368
+ throw new Error('inspector bundle was empty');
369
+ return inspectorCode;
370
+ }
371
+ throw new Error('canvas inspector bundle is missing; run npm run build');
372
+ }
@@ -0,0 +1,350 @@
1
+ "use strict";
2
+ (() => {
3
+ // src/canvas-path.ts
4
+ var TABLE_SECTION = /* @__PURE__ */ new Set(["tbody", "thead", "tfoot"]);
5
+ var SEGMENT = /^(\d+):([a-z][a-z0-9-]*)$/;
6
+ function collapseText(value) {
7
+ return (value ?? "").replace(/\s+/g, " ").trim().slice(0, 120);
8
+ }
9
+ function adoptElement(el, parent = null) {
10
+ const node = {
11
+ tag: el.tagName.toLowerCase(),
12
+ classes: el.classList ? [...el.classList] : [],
13
+ text: collapseText(el.textContent),
14
+ rawChildren: [],
15
+ parent
16
+ };
17
+ for (let i = 0; i < el.children.length; i++) node.rawChildren.push(adoptElement(el.children[i], node));
18
+ return node;
19
+ }
20
+ function visibleChildren(node) {
21
+ const out = [];
22
+ for (const child of node.rawChildren) {
23
+ if (node.tag === "table" && TABLE_SECTION.has(child.tag)) out.push(...child.rawChildren);
24
+ else out.push(child);
25
+ }
26
+ return out;
27
+ }
28
+ function parsePath(path) {
29
+ if (path === "") return [];
30
+ if (path.length > 500 || path.includes("//")) return null;
31
+ const parts = path.split("/");
32
+ const segs = [];
33
+ for (const part of parts) {
34
+ const match = SEGMENT.exec(part);
35
+ if (!match) return null;
36
+ const index = Number(match[1]);
37
+ if (!Number.isInteger(index) || index > 1e4 || String(index) !== match[1]) return null;
38
+ segs.push({ index, tag: match[2] });
39
+ }
40
+ return segs;
41
+ }
42
+ function formatPath(segs) {
43
+ return segs.map((seg) => `${seg.index}:${seg.tag}`).join("/");
44
+ }
45
+ function resolvePath(body, path) {
46
+ const segs = parsePath(path);
47
+ if (!segs) return null;
48
+ const breadcrumb = [{ path: "", tag: body.tag, classes: body.classes }];
49
+ const acc = [];
50
+ let current = body;
51
+ for (const seg of segs) {
52
+ const child = visibleChildren(current)[seg.index];
53
+ if (!child || child.tag !== seg.tag) return null;
54
+ acc.push(seg);
55
+ current = child;
56
+ breadcrumb.push({ path: formatPath(acc), tag: child.tag, classes: child.classes });
57
+ }
58
+ return { node: current, breadcrumb };
59
+ }
60
+ function pathTo(body, node) {
61
+ if (node === body) return "";
62
+ const parts = [];
63
+ let current = node;
64
+ while (current && current !== body) {
65
+ let parent = current.parent;
66
+ if (!parent) return null;
67
+ if (TABLE_SECTION.has(parent.tag) && parent.parent?.tag === "table") parent = parent.parent;
68
+ const index = visibleChildren(parent).indexOf(current);
69
+ if (index < 0) return null;
70
+ parts.push(`${index}:${current.tag}`);
71
+ current = parent;
72
+ }
73
+ if (current !== body) return null;
74
+ return parts.reverse().join("/");
75
+ }
76
+
77
+ // src/canvas-mention.ts
78
+ function mentionFrom(body, path) {
79
+ const found = resolvePath(body, path);
80
+ if (!found) return null;
81
+ const text = found.node.text.slice(0, 80);
82
+ const shown = text.length > 42 ? `${text.slice(0, 42)}\u2026` : text;
83
+ return {
84
+ path,
85
+ tag: found.node.tag,
86
+ classes: found.node.classes,
87
+ text,
88
+ breadcrumb: found.breadcrumb,
89
+ label: shown ? `${found.node.tag} \xB7 ${shown}` : found.node.tag
90
+ };
91
+ }
92
+
93
+ // src/canvas-inspector.ts
94
+ var CHANNEL = "canvas-inspect";
95
+ function meta(name) {
96
+ return document.querySelector(`meta[name="${name}"]`)?.getAttribute("content") ?? "";
97
+ }
98
+ function box(id, outline, fill) {
99
+ const el = document.createElement("div");
100
+ el.id = id;
101
+ el.setAttribute("aria-hidden", "true");
102
+ el.style.setProperty("all", "initial");
103
+ el.style.position = "fixed";
104
+ el.style.pointerEvents = "none";
105
+ el.style.zIndex = "2147483646";
106
+ el.style.boxSizing = "border-box";
107
+ el.style.display = "none";
108
+ el.style.outline = outline;
109
+ el.style.outlineOffset = "-2px";
110
+ el.style.background = fill;
111
+ document.documentElement.append(el);
112
+ return el;
113
+ }
114
+ function place(el, target) {
115
+ const rect = target.getBoundingClientRect();
116
+ el.style.display = "block";
117
+ el.style.left = `${rect.left}px`;
118
+ el.style.top = `${rect.top}px`;
119
+ el.style.width = `${Math.max(rect.width, 0)}px`;
120
+ el.style.height = `${Math.max(rect.height, 0)}px`;
121
+ }
122
+ var nonce = meta("dsh-inspect-nonce");
123
+ var parentOrigin = meta("dsh-parent-origin");
124
+ var pageName = meta("dsh-inspect-page");
125
+ function anchorPage(target) {
126
+ const anchor = target.closest("a");
127
+ if (!(anchor instanceof HTMLAnchorElement)) return null;
128
+ const href = anchor.getAttribute("href")?.trim() ?? "";
129
+ if (href === "" || href.startsWith("#")) return null;
130
+ let url;
131
+ try {
132
+ url = new URL(href, document.baseURI);
133
+ } catch {
134
+ return null;
135
+ }
136
+ const base = new URL(document.baseURI);
137
+ if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) return null;
138
+ let rel = url.pathname.slice(base.pathname.length);
139
+ try {
140
+ rel = decodeURIComponent(rel);
141
+ } catch {
142
+ return null;
143
+ }
144
+ if (!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\.html$/.test(rel)) return null;
145
+ return { path: rel, hash: url.hash };
146
+ }
147
+ if (nonce && parentOrigin && document.body) {
148
+ const hoverBox = box("dsh-hover", "2px solid #2563eb", "rgba(37, 99, 235, 0.12)");
149
+ const pinBox = box("dsh-pin", "2px solid #b45309", "rgba(180, 83, 9, 0.1)");
150
+ const tip = document.createElement("div");
151
+ tip.id = "dsh-tip";
152
+ tip.setAttribute("aria-hidden", "true");
153
+ tip.style.setProperty("all", "initial");
154
+ tip.style.position = "fixed";
155
+ tip.style.pointerEvents = "none";
156
+ tip.style.zIndex = "2147483647";
157
+ tip.style.display = "none";
158
+ tip.style.font = "12px/1.3 ui-sans-serif, system-ui, sans-serif";
159
+ tip.style.color = "#fff";
160
+ tip.style.background = "#1c1917";
161
+ tip.style.padding = "4px 8px";
162
+ tip.style.borderRadius = "6px";
163
+ tip.style.whiteSpace = "nowrap";
164
+ tip.style.maxWidth = "70vw";
165
+ tip.style.overflow = "hidden";
166
+ tip.style.textOverflow = "ellipsis";
167
+ document.documentElement.append(tip);
168
+ const body = adoptElement(document.body);
169
+ const elements = /* @__PURE__ */ new Map();
170
+ const nodes = /* @__PURE__ */ new WeakMap();
171
+ const index = (el, node) => {
172
+ nodes.set(el, node);
173
+ elements.set(node, el);
174
+ for (let i = 0; i < el.children.length; i++) index(el.children[i], node.rawChildren[i]);
175
+ };
176
+ index(document.body, body);
177
+ let armed = false;
178
+ let hoverEl = null;
179
+ let pinnedEl = null;
180
+ let hoverPath = "";
181
+ let queued = null;
182
+ let scheduled = false;
183
+ const post = (type, path, target) => {
184
+ const rect = target?.getBoundingClientRect();
185
+ const node = target ? nodes.get(target) : null;
186
+ window.parent.postMessage(
187
+ {
188
+ dsh: CHANNEL,
189
+ nonce,
190
+ type,
191
+ path,
192
+ tag: node?.tag ?? "",
193
+ classes: node?.classes ?? [],
194
+ text: node?.text ?? "",
195
+ rect: rect ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : { x: 0, y: 0, width: 0, height: 0 }
196
+ },
197
+ parentOrigin
198
+ );
199
+ };
200
+ const nodeFor = (el) => {
201
+ let current = el;
202
+ while (current && current !== document.documentElement) {
203
+ if (current.id.startsWith("dsh-") || current.tagName === "SCRIPT") {
204
+ current = current.parentElement;
205
+ continue;
206
+ }
207
+ const found = nodes.get(current);
208
+ if (found) return found;
209
+ current = current.parentElement;
210
+ }
211
+ return null;
212
+ };
213
+ const hideHover = () => {
214
+ hoverEl = null;
215
+ hoverPath = "";
216
+ hoverBox.style.display = "none";
217
+ tip.style.display = "none";
218
+ post("leave", "", null);
219
+ };
220
+ const showTip = (el, node, path) => {
221
+ const rect = el.getBoundingClientRect();
222
+ const mention = mentionFrom(body, path);
223
+ const trail = mention ? mention.breadcrumb.map((item) => item.classes[0] ? `${item.tag}.${item.classes[0]}` : item.tag).join(" / ") : node.tag;
224
+ tip.textContent = `${trail} ${Math.round(rect.width)}\xD7${Math.round(rect.height)}`;
225
+ tip.style.display = "block";
226
+ const top = rect.top < 28 ? rect.bottom + 6 : rect.top - 26;
227
+ tip.style.left = `${Math.max(rect.left, 4)}px`;
228
+ tip.style.top = `${top}px`;
229
+ };
230
+ const hover = (el) => {
231
+ if (!el) {
232
+ hideHover();
233
+ return;
234
+ }
235
+ const node = nodeFor(el);
236
+ if (!node) {
237
+ hideHover();
238
+ return;
239
+ }
240
+ const path = pathTo(body, node);
241
+ const target = path == null ? null : elements.get(resolvePath(body, path)?.node ?? node);
242
+ if (path == null || !target) {
243
+ hideHover();
244
+ return;
245
+ }
246
+ if (path === hoverPath) return;
247
+ hoverPath = path;
248
+ hoverEl = target;
249
+ place(hoverBox, target);
250
+ showTip(target, nodes.get(target) ?? node, path);
251
+ post("hover", path, target);
252
+ };
253
+ const pin = (el) => {
254
+ const node = nodeFor(el);
255
+ if (!node) return;
256
+ const path = pathTo(body, node);
257
+ if (path == null) return;
258
+ const target = elements.get(resolvePath(body, path)?.node ?? node);
259
+ if (!target) return;
260
+ pinnedEl = target;
261
+ place(pinBox, target);
262
+ post("select", path, target);
263
+ };
264
+ document.addEventListener("pointermove", (event) => {
265
+ if (!armed) return;
266
+ const hit = document.elementFromPoint(event.clientX, event.clientY);
267
+ queued = hit instanceof Element ? hit : null;
268
+ if (scheduled) return;
269
+ scheduled = true;
270
+ requestAnimationFrame(() => {
271
+ scheduled = false;
272
+ hover(queued);
273
+ });
274
+ });
275
+ document.documentElement.addEventListener("pointerleave", () => {
276
+ if (armed) hideHover();
277
+ });
278
+ document.addEventListener(
279
+ "click",
280
+ (event) => {
281
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
282
+ const target = event.target;
283
+ if (!(target instanceof Element)) return;
284
+ if (armed) {
285
+ event.preventDefault();
286
+ event.stopPropagation();
287
+ pin(target);
288
+ return;
289
+ }
290
+ const link = anchorPage(target);
291
+ if (!link) return;
292
+ if (link.path === pageName) {
293
+ if (!link.hash) event.preventDefault();
294
+ return;
295
+ }
296
+ event.preventDefault();
297
+ event.stopPropagation();
298
+ post("open", link.hash ? `${link.path}${link.hash}` : link.path, null);
299
+ },
300
+ true
301
+ );
302
+ document.addEventListener(
303
+ "scroll",
304
+ () => {
305
+ if (!armed) return;
306
+ if (pinnedEl) place(pinBox, pinnedEl);
307
+ if (hoverEl) {
308
+ place(hoverBox, hoverEl);
309
+ const node = nodes.get(hoverEl);
310
+ if (node) showTip(hoverEl, node, hoverPath);
311
+ }
312
+ },
313
+ true
314
+ );
315
+ window.addEventListener("message", (event) => {
316
+ if (event.source !== window.parent || event.origin !== parentOrigin) return;
317
+ const data = event.data;
318
+ if (!data || data.dsh !== CHANNEL || data.nonce !== nonce) return;
319
+ if (data.type === "hello") {
320
+ post("ready", "", document.body);
321
+ return;
322
+ }
323
+ if (data.type === "focus" && typeof data.anchor === "string" && /^[A-Za-z][\w-]{0,64}$/.test(data.anchor)) {
324
+ document.getElementById(data.anchor)?.scrollIntoView({ block: "start" });
325
+ return;
326
+ }
327
+ if (data.type === "arm") {
328
+ armed = true;
329
+ if (pinnedEl) place(pinBox, pinnedEl);
330
+ return;
331
+ }
332
+ if (data.type === "disarm") {
333
+ armed = false;
334
+ hideHover();
335
+ pinBox.style.display = "none";
336
+ return;
337
+ }
338
+ if (data.type !== "pin") return;
339
+ if (typeof data.path !== "string" || !parsePath(data.path)) return;
340
+ const found = resolvePath(body, data.path);
341
+ const el = found ? elements.get(found.node) : null;
342
+ if (!el) return;
343
+ pinnedEl = el;
344
+ if (!armed) return;
345
+ place(pinBox, el);
346
+ el.scrollIntoView({ block: "nearest" });
347
+ });
348
+ post("ready", "", document.body);
349
+ }
350
+ })();