dsh-design-studio 0.27.0 → 0.29.0

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.
package/lib/index.js CHANGED
@@ -36,6 +36,9 @@
36
36
  * GET /dsh-design-studio/api/bundle?session=&key=&v=&parent= 远程看:这一屏连同样式、图片打成一份 → { html, deps }(放进沙盒 iframe;deps 改了再取)
37
37
  * POST /dsh-design-studio/api/phone 手机上看:{ session, on: true, path } 开局域网入口(给链接和二维码)、
38
38
  * { on: false } 关掉、{ follow: path } 电脑上换了一屏手机跟着跳
39
+ * POST /dsh-design-studio/api/pubshare 公网链接(实验):{ session, on: true, …整套演示的参数 } 用 cloudflared 临时通道放出整套 HTML 演示、
40
+ * { on: false } 关掉、{ peek: true } 看状态(带二维码)、{ update: true, … } 换参数、
41
+ * { download: true } 下载 cloudflared(人点了才下)、{ cancel: true } 取消下载
39
42
  *
40
43
  * 页面本身由 serve.js 开的独立端口提供(见那边的说明)。
41
44
  */
@@ -56,10 +59,11 @@ import { createLibraryRoutes } from './gallery/routes.js'
56
59
  import { createMarket } from './gallery/market.js'
57
60
  import { createMarketRoutes } from './gallery/market-routes.js'
58
61
  import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, ratioNote, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
59
- import { createTracker, parseTarget, findRule, KINDS } from './core.js'
62
+ import { createTracker, parseTarget, findRule, allScreens, classSigs, exportOrder, KINDS } from './core.js'
60
63
  import { createDrafts } from './draft.js'
61
64
  import { createHistory } from './history.js'
62
65
  import { createPhone } from './phone.js'
66
+ import { createPublicShare } from './tunnel.js'
63
67
  import { qrMatrix } from './qr.js'
64
68
  import { makePdf, makePptx, jpegInfo } from './doc.js'
65
69
  import { createBrowser } from './browser.js'
@@ -70,7 +74,8 @@ import { saveFrame, listFrames, frameSection } from './frames.js'
70
74
  import { readTweaks, applyTweaks, lintTweaks } from './tweaks.js'
71
75
  import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
72
76
  import { createImpl } from './impl.js'
73
- import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots } from './handoff.js'
77
+ import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, implServe, defaultDest, pickedDest, within, pinRoots, frameCss } from './handoff.js'
78
+ import { editsNotice, noticeMessage, langOf } from './edits.js'
74
79
 
75
80
  export const name = 'dsh-design-studio'
76
81
  export const inject = ['webServer']
@@ -81,7 +86,10 @@ const LOOPBACK_HOST = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i
81
86
  const MAX_BODY = 64 * 1024
82
87
  const MAX_EXPORT = 48 * 1024 * 1024 // 导出图片的请求体(base64)
83
88
  const MAX_DOC = 160 * 1024 * 1024 // 导出 PDF / PPT 的请求体(几十屏的 JPEG,base64)
84
- const MAX_PAGES = 60
89
+ const MAX_PAGES = 1000 // PDF / PPT 最多几页(#29:画布只显示 60 屏,导出要全部)
90
+ const DOC_CHUNK = 40 // 分批传的时候一批最多几页(截图一张几百 KB,几百屏一次传不动)
91
+ const DOC_JOB_BYTES = 1024 * 1024 * 1024 // 一份 PDF / PPT 攒的图片最多这么多
92
+ const DOC_JOB_TTL = 10 * 60 * 1000 // 一批传完到下一批最多等多久(右侧栏关了、换了设计就别一直占着内存)
85
93
  const CHECK_WAIT = 30000 // check_design 等右侧栏量完的最长时间(右侧栏每屏最多等 6 秒载入 + 15 秒量完,几屏一起量)
86
94
  const HISTORY_DIR = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'history')
87
95
  // 每个会话预览的是什么,存这里(DSH 重启后接着显示)
@@ -573,7 +581,7 @@ export const handoffTool = {
573
581
  if (framework === 'same' && !project.framework) return { text: `${dest} 里没有认得出的前端项目(package.json 里没有 React / Vue / Next / uni-app …,也不是 HBuilderX 或微信原生小程序的项目):framework 选 react、vue、next、html、uniapp 或 weapp。` }
574
582
  let r
575
583
  try {
576
- r = await buildHandoff(studio.browser, { root: t.root, screens: pick.list, kind, size, framework, dest, project, system: systemOfDir(t.root), annotations: studio.annotations > 0 ? readAnnotations(t.root) : null })
584
+ r = await buildHandoff(studio.browser, { root: t.root, screens: pick.list, kind, size, framework, dest, project, system: systemOfDir(t.root), annotations: studio.annotations > 0 ? readAnnotations(t.root) : null, tuned: studio.tracker.versions(id) })
577
585
  } catch (e) {
578
586
  return { text: `没写成交接包:${String((e && e.message) || e).slice(0, 200)}` }
579
587
  }
@@ -979,6 +987,20 @@ export function apply(ctx) {
979
987
  }, 'dsh-design-studio: headless browser')
980
988
  const phone = createPhone({ upstream: (session) => tracker.snapshot(session).origin || '', log })
981
989
  ctx.effect(() => () => phone.stopAll(), 'dsh-design-studio: phone links')
990
+ // 公网链接(#27):只放整套 HTML 演示,每次有人打开按现在的文件打包(文件没改就用上次的)
991
+ const pub = createPublicShare({
992
+ build: (p) => {
993
+ const { pack, files } = packDesign(p.root, 0, p)
994
+ return { html: pack.html, deps: files }
995
+ },
996
+ // 这个会话换了设计(或关了):关掉,别把不在眼前的设计一直开在公网上(插件自己每 5 秒看一眼,不靠右侧栏开着)
997
+ alive: (session, p) => {
998
+ const t = tracker.stateOf(session).target
999
+ return !!(t && t.kind === 'file' && t.root === p.root)
1000
+ },
1001
+ log,
1002
+ })
1003
+ ctx.effect(() => () => { pub.stopAll(); pub.cancelTool() }, 'dsh-design-studio: public links')
982
1004
 
983
1005
  // ── 接口 ──────────────────────────────────────────────────────────────────
984
1006
 
@@ -1047,7 +1069,7 @@ export function apply(ctx) {
1047
1069
  let tweaks = null
1048
1070
  if (t && t.kind === 'file') { try { tweaks = readTweaks(t.root) } catch (e) { log(e) } }
1049
1071
  const snap = tracker.snapshot(session)
1050
- json(res, 200, { ...snap, impl: implStore.list(implRoot(snap)), strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, tweaks, ...annotsField(session, new URL(req.url, 'http://x').searchParams.get('an')), ...(c ? { checkReq: c.id } : {}) })
1072
+ json(res, 200, { ...snap, impl: implStore.list(implRoot(snap)), strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, pub: pub.status(session, { brief: true }), tweaks, ...annotsField(session, new URL(req.url, 'http://x').searchParams.get('an')), ...(c ? { checkReq: c.id } : {}) })
1051
1073
  }
1052
1074
 
1053
1075
  /** 正在看的几屏里,哪些是别人做的、没改过的(地址列表):右侧栏给它们的 iframe 加沙盒、不给剪贴板 */
@@ -1291,7 +1313,8 @@ export function apply(ctx) {
1291
1313
  // 输入框里写的相对路径按会话目录算(新会话也问 DSH 要)
1292
1314
  const target = parseTarget(body.target, await sessionCwd(session))
1293
1315
  await tracker.setTarget(session, target, { source: 'user', popup: false })
1294
- json(res, 200, { ...tracker.snapshot(session), ...annotsField(session) })
1316
+ // 换了设计,公网链接马上关(右侧栏要马上知道,不等下一次刷新)
1317
+ json(res, 200, { ...tracker.snapshot(session), ...annotsField(session), pub: pub.status(session, { brief: true }) })
1295
1318
  } catch (e) {
1296
1319
  json(res, 400, { error: e.message })
1297
1320
  }
@@ -1308,7 +1331,7 @@ export function apply(ctx) {
1308
1331
  for (const k of ['kind', 'size', 'view', 'focus']) if (typeof body[k] === 'string') patch[k] = body[k]
1309
1332
  try {
1310
1333
  await tracker.setView(session, patch)
1311
- json(res, 200, { ...tracker.snapshot(session), ...annotsField(session) })
1334
+ json(res, 200, { ...tracker.snapshot(session), ...annotsField(session), pub: pub.status(session, { brief: true }) })
1312
1335
  } catch (e) {
1313
1336
  json(res, 400, { error: e.message })
1314
1337
  }
@@ -1321,6 +1344,7 @@ export function apply(ctx) {
1321
1344
  try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1322
1345
  tracker.clear(String(body.session || ''))
1323
1346
  phone.stop(String(body.session || ''))
1347
+ pub.stop(String(body.session || ''))
1324
1348
  json(res, 200, tracker.snapshot(String(body.session || '')))
1325
1349
  }
1326
1350
 
@@ -1363,12 +1387,75 @@ export function apply(ctx) {
1363
1387
  let body
1364
1388
  try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1365
1389
  try {
1366
- json(res, 200, tracker.editStyle(String(body.session || ''), { key: body.key, loc: body.loc, css: body.css, name: body.name }))
1390
+ const id = String(body.session || '')
1391
+ // 右侧栏点的时候是哪套设计:中途换了(这次保存晚到)就不写,免得写进另一套同名的屏
1392
+ if (typeof body.target === 'string' && body.target !== targetKeyOf(tracker.stateOf(id).target)) return json(res, 200, { ok: false, reason: 'moved' })
1393
+ const rule = body.rule && typeof body.rule === 'object' ? body.rule : null
1394
+ if (rule) return json(res, 200, styleToRule(id, body, rule))
1395
+ json(res, 200, tracker.editStyle(id, { key: body.key, loc: body.loc, css: body.css, name: body.name, imp: Array.isArray(body.imp) ? body.imp.slice(0, 20) : [] }))
1367
1396
  } catch (e) {
1368
1397
  json(res, 500, { error: e.message })
1369
1398
  }
1370
1399
  }
1371
1400
 
1401
+ /**
1402
+ * 调样式「各屏一起改」:写进右侧栏指的那条规则({ href, sel, n, cls },href 是预览地址上的样式表)。
1403
+ * 只认这个会话预览的本地目录里的 .css;外框的样式表(锁着的)不写。写不了给 { ok: false, reason },右侧栏退回只改这一处
1404
+ */
1405
+ function styleToRule(id, body, rule) {
1406
+ const st = tracker.stateOf(id)
1407
+ const t = st && st.target
1408
+ if (!t || t.kind !== 'file' || !st.origin) return { ok: false, reason: 'not-file' }
1409
+ let u
1410
+ try { u = new URL(String(rule.href || '')) } catch { return { ok: false, reason: 'no-rule' } }
1411
+ if (u.origin !== st.origin || u.pathname.startsWith('/__dsh_design__/') || !/\.css$/i.test(u.pathname)) return { ok: false, reason: 'no-rule' }
1412
+ const hit = resolveInRoot(t.root, u.pathname)
1413
+ if (!hit || !hit.real) return { ok: false, reason: 'no-rule' }
1414
+ const key = String(body.key || path.basename(t.file))
1415
+ let html = ''
1416
+ try { html = fs.readFileSync(path.join(t.root, path.basename(key)), 'utf8') } catch { /* 读不了就当没套外框 */ }
1417
+ const locked = new Set(frameCss(t.root, [html]).map((x) => x.toLowerCase()))
1418
+ if (locked.has(path.basename(hit.abs).toLowerCase())) return { ok: false, reason: 'frame' }
1419
+ return tracker.editRule(id, { key, loc: body.loc, file: hit.abs, sel: String(rule.sel || '').slice(0, 400), n: Math.max(0, Math.floor(Number(rule.n) || 0)), css: body.css, name: body.name, cls: String(rule.cls || '').slice(0, 80) })
1420
+ }
1421
+
1422
+ /**
1423
+ * 「各屏一起改」默认勾不勾(#28):设计里所有屏(收起来的也算)带这个 class 的元素,是不是都和选中的同一种(sig:picker 算的「标签|class」)。
1424
+ * 有一处不一样(.btn 既是按钮又是链接)、读不了、太大:same: false,右侧栏默认只改这一处。
1425
+ * 按目录 + class 记一下(各屏的修改时间、大小都没变就不重读),点来点去不用每次全读
1426
+ */
1427
+ const shareSeen = new Map() // `${root}|${cls}` → { stamp, sigs: Set(sig) },只留最近 20 个
1428
+ async function shareCheckRoute(req, res) {
1429
+ if (!admit(req, res)) return
1430
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1431
+ let body
1432
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1433
+ const st = tracker.stateOf(String(body.session || ''))
1434
+ const t = st && st.target
1435
+ const cls = String(body.cls || '')
1436
+ const sig = String(body.sig || '')
1437
+ if (!t || t.kind !== 'file' || !/^-?[_a-zA-Z][\w-]{0,79}$/.test(cls) || !sig) return json(res, 200, { same: false })
1438
+ const files = allScreens(t.root).slice(0, MAX_PAGES)
1439
+ const stats = files.map((k) => { try { return fs.statSync(path.join(t.root, k)) } catch { return null } })
1440
+ const stamp = files.map((k, i) => (stats[i] ? `${k}:${stats[i].mtimeMs}:${stats[i].size}` : '')).join('|')
1441
+ const ck = `${t.root}|${cls}`
1442
+ let hit = shareSeen.get(ck)
1443
+ if (!hit || hit.stamp !== stamp) {
1444
+ const sigs = new Set()
1445
+ for (const [i, k] of files.entries()) {
1446
+ if (!stats[i]) continue // 刚删掉的屏不算
1447
+ if (stats[i].size > 2 * 1024 * 1024) { sigs.add('?'); break }
1448
+ try { for (const x of classSigs(fs.readFileSync(path.join(t.root, k), 'utf8'), cls)) sigs.add(x) } catch { sigs.add('?') }
1449
+ if (sigs.size > 1) break
1450
+ }
1451
+ hit = { stamp, sigs }
1452
+ shareSeen.delete(ck)
1453
+ shareSeen.set(ck, hit)
1454
+ while (shareSeen.size > 20) shareSeen.delete(shareSeen.keys().next().value)
1455
+ }
1456
+ json(res, 200, { target: targetKeyOf(t), same: hit.sigs.size === 1 && hit.sigs.has(sig) })
1457
+ }
1458
+
1372
1459
  /**
1373
1460
  * 调样式交给模型前:每项样式胜出的那条规则在源码第几行(picker 给 { href, sel, n },这里在设计目录的文件里找)。
1374
1461
  * 只认这个会话预览的本地目录里的文件;开发服务器的样式多半是编译出来的,不找
@@ -1625,26 +1712,98 @@ export function apply(ctx) {
1625
1712
  saveExport(res, String(body.session || ''), body.name, 'png', buf)
1626
1713
  }
1627
1714
 
1628
- /** 几屏拼成 PDF / PPT:每屏一页,页面大小按那一屏的 CSS 尺寸 */
1715
+ /**
1716
+ * 屏多过上限(#29):导出用的全部屏,按导出的先后(显示的照右侧栏的顺序,收起来的照设计清单 / 生成先后插回原位),带页面标题(导出的目录、演示的下拉里用)。
1717
+ * 右侧栏导出前现问这一份,不靠它自己记的(刚加的屏、改了名的收起来的屏,它都还没轮询到)。没收起来的给空(右侧栏就用显示的这些)
1718
+ */
1719
+ async function hiddenRoute(req, res) {
1720
+ if (!admit(req, res)) return
1721
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1722
+ let body
1723
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
1724
+ const session = String(body.session || '')
1725
+ const st = tracker.stateOf(session)
1726
+ const t = st.target
1727
+ const hid = tracker.hiddenScreens(session)
1728
+ if (!hid.length) return json(res, 200, { target: targetKeyOf(t), list: [] })
1729
+ const on = new Set(hid)
1730
+ const all = exportOrder(st.screens, hid, allScreens(t.root))
1731
+ const keys = all.slice(0, MAX_PAGES) // 一次最多导出这么多屏,多的(排在最后的)右侧栏提示没导出
1732
+ const list = keys.map((key) => {
1733
+ let title = ''
1734
+ try {
1735
+ const fd = fs.openSync(path.join(t.root, key), 'r')
1736
+ try { const buf = Buffer.alloc(8192); const n = fs.readSync(fd, buf, 0, buf.length, 0); title = (/<title[^>]*>([^<]{1,120})<\/title>/i.exec(buf.subarray(0, n).toString('utf8')) || [])[1] || '' } finally { fs.closeSync(fd) }
1737
+ } catch { title = '' }
1738
+ return { key, title: title.replace(/\s+/g, ' ').trim(), hidden: on.has(key) }
1739
+ })
1740
+ json(res, 200, { target: targetKeyOf(t), list, cut: all.length - keys.length })
1741
+ }
1742
+
1743
+ // PDF / PPT 分批传(#29):几百屏的截图一次传不动,右侧栏每截几十屏传一批,最后一批带 done 再拼。job → { session, pages, bytes, at }
1744
+ const docJobs = new Map()
1745
+ const sweepDocJobs = () => { const old = Date.now() - DOC_JOB_TTL; for (const [k, j] of docJobs) if (j.at < old) docJobs.delete(k) }
1746
+ // 导出到一半退出 / 右侧栏关了:没人再来传,也按时清掉攒着的截图(不等下一次导出)
1747
+ ctx.effect(() => { const iv = setInterval(sweepDocJobs, 60 * 1000); if (iv.unref) iv.unref(); return () => { clearInterval(iv); docJobs.clear() } }, 'dsh-design-studio: doc jobs')
1748
+
1749
+ /** 一页截图:JPEG + CSS 尺寸 + 标题 + 跳转链接;不是 JPEG 给 null */
1750
+ function docPage(p) {
1751
+ const jpg = Buffer.from(String((p && p.jpg) || ''), 'base64')
1752
+ const info = jpegInfo(jpg)
1753
+ if (!info) return null
1754
+ // 页面大小(CSS 像素):没给或不像话就按图片的一半算(截图是 2 倍)
1755
+ const ok = (v) => Number.isFinite(+v) && +v >= 16 && +v <= 30000
1756
+ const w = ok(p.w) && ok(p.h) ? +p.w : info.width / 2
1757
+ const h = ok(p.w) && ok(p.h) ? +p.h : info.height / 2
1758
+ // 跳转链接原样带过去,doc.js 里挑掉不合法的;分批传的链接写的是目标屏的 key(到最后才知道它是第几页)
1759
+ return { jpg, w, h, key: typeof p.key === 'string' ? p.key.slice(0, 300) : '', title: String(p.title || '').slice(0, 80), links: Array.isArray(p.links) ? p.links.slice(0, 50) : [] }
1760
+ }
1761
+
1762
+ /** 几屏拼成 PDF / PPT:每屏一页,页面大小按那一屏的 CSS 尺寸。带 job 的是分批传:没 done 的只攒着 */
1629
1763
  async function docRoute(req, res) {
1630
1764
  if (!admit(req, res)) return
1631
1765
  if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1632
1766
  let body
1633
1767
  try { body = await readBody(req, MAX_DOC) } catch (e) { return json(res, 400, { error: e.message }) }
1768
+ const session = String(body.session || '')
1769
+ const job = typeof body.job === 'string' && /^[a-z0-9]{8,40}$/i.test(body.job) ? body.job : ''
1770
+ let pages = []
1771
+ if (job) {
1772
+ sweepDocJobs()
1773
+ if (body.cancel) { if (docJobs.get(job)?.session === session) docJobs.delete(job); return json(res, 200, { ok: true }) } // 导出到一半换了设计
1774
+ // at:右侧栏说之前已经传了几页。前面传过、这里却没了(等太久被清掉、DSH 重启过),或页数对不上:别拿半截拼,整份重来
1775
+ const sent = typeof body.at === 'number' ? Math.max(0, Math.floor(body.at)) : -1
1776
+ let j = docJobs.get(job)
1777
+ if (!j) {
1778
+ if (sent > 0) return json(res, 410, { error: 'jobGone' })
1779
+ j = { session, pages: [], bytes: 0, at: Date.now() }
1780
+ docJobs.set(job, j)
1781
+ }
1782
+ if (j.session !== session) return json(res, 400, { error: 'job' })
1783
+ if (sent >= 0 && j.pages.length !== sent) { docJobs.delete(job); return json(res, 409, { error: 'jobGone' }) }
1784
+ for (const p of Array.isArray(body.pages) ? body.pages.slice(0, DOC_CHUNK) : []) {
1785
+ const pg = docPage(p)
1786
+ if (!pg) { docJobs.delete(job); return json(res, 400, { error: '不是 JPEG' }) }
1787
+ j.bytes += pg.jpg.length
1788
+ if (j.pages.length >= MAX_PAGES || j.bytes > DOC_JOB_BYTES) { docJobs.delete(job); return json(res, 413, { error: 'tooBig' }) }
1789
+ j.pages.push(pg)
1790
+ }
1791
+ j.at = Date.now()
1792
+ if (!body.done) return json(res, 200, { ok: true, n: j.pages.length })
1793
+ docJobs.delete(job)
1794
+ pages = j.pages
1795
+ // 链接:目标屏的 key 换成第几页(没截上的屏不算)
1796
+ const at = new Map(pages.map((p, i) => [p.key, i]))
1797
+ for (const p of pages) p.links = p.links.map((l) => (l && typeof l.key === 'string' ? { x: l.x, y: l.y, w: l.w, h: l.h, to: at.has(l.key) ? at.get(l.key) : -1 } : l)).filter((l) => l && l.to >= 0)
1798
+ } else {
1799
+ for (const p of Array.isArray(body.pages) ? body.pages.slice(0, MAX_PAGES) : []) {
1800
+ const pg = docPage(p)
1801
+ if (!pg) return json(res, 400, { error: '不是 JPEG' })
1802
+ pages.push(pg)
1803
+ }
1804
+ }
1634
1805
  const format = body.format === 'pdf' || body.format === 'pptx' ? body.format : ''
1635
1806
  if (!format) return json(res, 400, { error: 'format 只能是 pdf / pptx' })
1636
- const pages = []
1637
- for (const p of Array.isArray(body.pages) ? body.pages.slice(0, MAX_PAGES) : []) {
1638
- const jpg = Buffer.from(String((p && p.jpg) || ''), 'base64')
1639
- const info = jpegInfo(jpg)
1640
- if (!info) return json(res, 400, { error: '不是 JPEG' })
1641
- // 页面大小(CSS 像素):没给或不像话就按图片的一半算(截图是 2 倍)
1642
- const ok = (v) => Number.isFinite(+v) && +v >= 16 && +v <= 30000
1643
- const w = ok(p.w) && ok(p.h) ? +p.w : info.width / 2
1644
- const h = ok(p.w) && ok(p.h) ? +p.h : info.height / 2
1645
- // 跳转链接原样带过去,doc.js 里挑掉不合法的
1646
- pages.push({ jpg, w, h, title: String(p.title || '').slice(0, 80), links: Array.isArray(p.links) ? p.links.slice(0, 50) : [] })
1647
- }
1648
1807
  if (!pages.length) return json(res, 400, { error: '没有页面' })
1649
1808
  const title = String(body.title || '').slice(0, 120)
1650
1809
  let buf
@@ -1655,25 +1814,12 @@ export function apply(ctx) {
1655
1814
  } catch (e) {
1656
1815
  return json(res, 400, { error: e.message })
1657
1816
  }
1658
- if (targetMoved(res, String(body.session || ''), body.target)) return
1659
- saveExport(res, String(body.session || ''), body.name, format, buf)
1817
+ if (targetMoved(res, session, body.target)) return
1818
+ saveExport(res, session, body.name, format, buf)
1660
1819
  }
1661
1820
 
1662
- /**
1663
- * 整套 HTML 演示(#26):本地文件的设计,所有屏打进一个 .html(见 htmlpack.js),存进 exports/。
1664
- * 屏、版本、画幅、深浅色、外壳、调节滑块还没存的值都按右侧栏眼前的来;不截图,几秒出来
1665
- */
1666
- async function htmlPackRoute(req, res) {
1667
- if (!admit(req, res)) return
1668
- if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1669
- let body
1670
- try { body = await readBody(req, 1024 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
1671
- const session = String(body.session || '')
1672
- const st = tracker.stateOf(session)
1673
- const t = st && st.target
1674
- if (!t || t.kind !== 'file') return json(res, 400, { error: 'not-file' })
1675
- if (targetMoved(res, session, body.target)) return
1676
- const v = Math.max(0, Math.floor(Number(body.v) || 0))
1821
+ /** 整套 HTML 演示的参数(导出和公网链接共用):挑掉不合法、重复的屏;画幅、深浅色、调节值按右侧栏给的。没有屏给 null */
1822
+ function packParams(body) {
1677
1823
  const okKey = (k) => typeof k === 'string' && /^[^\\]+\.html?$/i.test(k) && !k.split('/').some((p) => !p || p === '.' || p === '..')
1678
1824
  const seen = new Set()
1679
1825
  const screens = []
@@ -1682,33 +1828,62 @@ export function apply(ctx) {
1682
1828
  seen.add(s.key)
1683
1829
  screens.push({ key: s.key, label: String(s.label || s.key).slice(0, 80), top: s.top === true })
1684
1830
  }
1685
- if (!screens.length) return json(res, 400, { error: 'noScreens' })
1686
- const kind = typeof body.kind === 'string' ? body.kind : 'web'
1831
+ if (!screens.length) return null
1687
1832
  const dim = (x, d) => (Number.isFinite(+x) && +x >= 100 && +x <= 8000 ? Math.round(+x) : d)
1688
- const w = dim(body.w, 1280), h = dim(body.h, 800)
1833
+ const tw = body.tweak && typeof body.tweak === 'object' ? body.tweak : null
1834
+ const plain = (o) => Object.fromEntries(Object.entries(o && typeof o === 'object' ? o : {}).filter(([k, x]) => typeof k === 'string' && k.length < 80 && (typeof x === 'string' || typeof x === 'number' || x === null || typeof x === 'boolean')).slice(0, 200))
1835
+ return {
1836
+ screens,
1837
+ kind: typeof body.kind === 'string' ? body.kind : 'web',
1838
+ w: dim(body.w, 1280),
1839
+ h: dim(body.h, 800),
1840
+ os: body.os === 'win' ? 'win' : '',
1841
+ dark: body.dark === true,
1842
+ scheme: body.scheme === 'dark' ? 'dark' : 'light',
1843
+ tweak: tw ? { vars: plain(tw.vars), attrs: plain(tw.attrs) } : null,
1844
+ title: String(body.title || '').slice(0, 120),
1845
+ lang: body.lang === 'en' ? 'en' : 'zh',
1846
+ fit: body.fit === true,
1847
+ }
1848
+ }
1849
+
1850
+ /** 打包一个设计目录(v 是历史版本,0 = 现在的文件):deps 是读过的相对路径,files 是对应的文件(公网链接按它们判断要不要重新打包) */
1851
+ function packDesign(root, v, params) {
1689
1852
  const deps = new Set()
1853
+ const files = new Set()
1690
1854
  const read = (rel) => {
1691
1855
  deps.add(rel)
1692
- const f = bundleFile(t.root, v, rel)
1856
+ const f = bundleFile(root, v, rel)
1857
+ files.add(f || path.join(root, ...rel.split('/')))
1693
1858
  if (!f) return null
1694
1859
  const s = fs.statSync(f)
1695
1860
  return s.isFile() && s.size <= BUNDLE_MAX ? fs.readFileSync(f) : null
1696
1861
  }
1697
- const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(t.root))
1698
- const tw = body.tweak && typeof body.tweak === 'object' ? body.tweak : null
1699
- const plain = (o) => Object.fromEntries(Object.entries(o && typeof o === 'object' ? o : {}).filter(([k, x]) => typeof k === 'string' && k.length < 80 && (typeof x === 'string' || typeof x === 'number' || x === null || typeof x === 'boolean')).slice(0, 200))
1700
- let pack
1862
+ const strictOf = (page) => library.strictHtml(page) || market.strictHtml(page) || (v > 0 && library.strictVersions(root))
1863
+ const pack = buildPack({ ...params, read, strictOf })
1864
+ return { pack, deps, files: [...files] }
1865
+ }
1866
+
1867
+ /**
1868
+ * 整套 HTML 演示(#26):本地文件的设计,所有屏打进一个 .html(见 htmlpack.js),存进 exports/。
1869
+ * 屏、版本、画幅、深浅色、外壳、调节滑块还没存的值都按右侧栏眼前的来;不截图,几秒出来
1870
+ */
1871
+ async function htmlPackRoute(req, res) {
1872
+ if (!admit(req, res)) return
1873
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1874
+ let body
1875
+ try { body = await readBody(req, 1024 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
1876
+ const session = String(body.session || '')
1877
+ const st = tracker.stateOf(session)
1878
+ const t = st && st.target
1879
+ if (!t || t.kind !== 'file') return json(res, 400, { error: 'not-file' })
1880
+ if (targetMoved(res, session, body.target)) return
1881
+ const v = Math.max(0, Math.floor(Number(body.v) || 0))
1882
+ const params = packParams(body)
1883
+ if (!params) return json(res, 400, { error: 'noScreens' })
1884
+ let pack, deps
1701
1885
  try {
1702
- pack = buildPack({
1703
- screens, read, strictOf, kind, w, h,
1704
- os: body.os === 'win' ? 'win' : '',
1705
- dark: body.dark === true,
1706
- scheme: body.scheme === 'dark' ? 'dark' : 'light',
1707
- tweak: tw ? { vars: plain(tw.vars), attrs: plain(tw.attrs) } : null,
1708
- title: String(body.title || '').slice(0, 120),
1709
- lang: body.lang === 'en' ? 'en' : 'zh',
1710
- fit: body.fit === true,
1711
- })
1886
+ ;({ pack, deps } = packDesign(t.root, v, params))
1712
1887
  } catch (e) {
1713
1888
  return json(res, e.code ? 400 : 500, { error: e.code || e.message })
1714
1889
  }
@@ -1791,6 +1966,44 @@ export function apply(ctx) {
1791
1966
  json(res, 200, st.on ? { ...st, qr: qrMatrix(st.url).map((row) => row.map((c) => (c ? 1 : 0)).join('')) } : st)
1792
1967
  }
1793
1968
 
1969
+ /**
1970
+ * 公网链接(#27,实验):{ session, on: true, …整套演示的参数 } 开(开着就换参数),{ on: false } 关,
1971
+ * { peek: true } 只看状态(连上了带二维码)。只能右侧栏里人点开,不给模型工具
1972
+ */
1973
+ async function pubShareRoute(req, res) {
1974
+ if (!admit(req, res)) return
1975
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
1976
+ let body
1977
+ try { body = await readBody(req, 1024 * 1024) } catch (e) { return json(res, 400, { error: e.message }) }
1978
+ const session = String(body.session || '')
1979
+ if (!session) return json(res, 400, { error: '缺 session' })
1980
+ const withQr = (x) => (x.on && x.url ? { ...x, qr: qrMatrix(x.url).map((row) => row.map((c) => (c ? 1 : 0)).join('')) } : x)
1981
+ if (body.on === false) {
1982
+ pub.stop(session)
1983
+ return json(res, 200, { ...pub.status(session), tool: pub.hasTool() })
1984
+ }
1985
+ // 看状态:顺带说本机有没有 cloudflared(没有的话右侧栏先请人下载)
1986
+ if (body.peek === true) return json(res, 200, { ...withQr(pub.status(session)), tool: pub.hasTool() })
1987
+ // 人点了「下载」:从 Cloudflare 官方 GitHub 下到插件自己的目录,进度在 peek 里;「取消」停下
1988
+ if (body.download === true || body.cancel === true) {
1989
+ if (body.cancel === true) pub.cancelTool()
1990
+ else pub.fetchTool()
1991
+ return json(res, 200, { ...pub.status(session), tool: pub.hasTool() })
1992
+ }
1993
+ const t = tracker.stateOf(session).target
1994
+ if (!t || t.kind !== 'file') return json(res, 400, { error: 'not-file' })
1995
+ if (targetMoved(res, session, body.target)) return
1996
+ const params = packParams(body)
1997
+ if (!params) return json(res, 400, { error: 'noScreens' })
1998
+ const p = { root: t.root, ...params }
1999
+ // 右侧栏换了屏、画幅、深浅色:开着就跟着换,没开不新开(开要人点)
2000
+ if (body.update === true) return json(res, 200, { ok: pub.update(session, p) })
2001
+ const r = await pub.start(session, p, { name: params.title || path.basename(t.root) })
2002
+ // 没开起来的原因(没装 cloudflared、打包不出来)start 直接给;开着的照状态给
2003
+ const now = pub.status(session)
2004
+ json(res, 200, { ...withQr(now.on ? now : { ...now, ...r }), tool: pub.hasTool() })
2005
+ }
2006
+
1794
2007
  // 设计库:我的作品、灵感、打 zip、拖 zip 进来用
1795
2008
  const inspiration = createInspiration({ log })
1796
2009
  /**
@@ -1835,7 +2048,7 @@ export function apply(ctx) {
1835
2048
  })
1836
2049
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
1837
2050
 
1838
- const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, edit: editRoute, style: styleRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
2051
+ const routes = { works: lib.works, workthumb: lib.workthumb, scrthumb: canvasThumbs.route, pack: lib.pack, usezip: lib.usezip, ghauth: lib.ghauth, submit: lib.submit, inspire: lib.inspire, inspimg: lib.inspimg, ...mk, state, open: openRoute, view: viewRoute, close: closeRoute, history: historyRoute, restore: restoreRoute, hidden: hiddenRoute, edit: editRoute, style: styleRoute, sharecheck: shareCheckRoute, bundle: bundleRoute, ref: refRoute, export: exportRoute, doc: docRoute, htmlpack: htmlPackRoute, pubshare: pubShareRoute, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, frames: framesRoute, systhumb: systhumbRoute, project: projectRoute, impl: implRoute, implcmp: implCmpRoute, implshot: implShotRoute }
1839
2052
  for (const [key, handler] of Object.entries(routes)) {
1840
2053
  ctx.effect(() => ctx.webServer.register({
1841
2054
  kind: 'exact',
@@ -1859,6 +2072,32 @@ export function apply(ctx) {
1859
2072
  log(e)
1860
2073
  }
1861
2074
  })
2075
+ // 会话归档了:它的公网链接马上关(面板进不去了,别让链接一直开到点)。老版本 DSH 没有这个事件,就只是收不到
2076
+ ctx.on('workspace/session-archived', (req) => {
2077
+ try {
2078
+ const id = req && req.sessionId
2079
+ if (id) pub.stop(String(id))
2080
+ } catch (e) {
2081
+ log(e)
2082
+ }
2083
+ }, { global: true })
2084
+ // 用户在右侧栏亲手改了设计:模型下一步开始前补一条说明(DSH 自带的时间、操作卡片提醒也是这么加的),
2085
+ // 免得它凭自己之前写的内容接着改、做进项目时用回旧样子(#28)。老版本 DSH 没有这个事件,就只是收不到
2086
+ ctx.on('agent/pre-step', async (payload, next) => {
2087
+ const decision = typeof next === 'function' ? await next() : undefined
2088
+ try {
2089
+ if (!decision || decision.kind !== 'enter' || !Array.isArray(decision.messages) || (payload && payload.signal && payload.signal.aborted)) return decision
2090
+ const id = payload && payload.agent && payload.agent.session && payload.agent.session.id
2091
+ if (!id) return decision
2092
+ const edits = tracker.takeEdits(String(id))
2093
+ const note = editsNotice(edits, langOf(decision.messages))
2094
+ if (!note) return decision
2095
+ return { ...decision, messages: [...decision.messages, noticeMessage(note, crypto.randomUUID())] }
2096
+ } catch (e) {
2097
+ log(e)
2098
+ return decision
2099
+ }
2100
+ }, { prepend: true })
1862
2101
  // 模型边说边推的流:写大文件时参数要流好几分钟,靠它提前知道在写哪个文件(老版本 DSH 没有这个事件,就只是收不到)
1863
2102
  ctx.on('agent/assistant-stream', (e) => {
1864
2103
  try {
package/lib/picker.js CHANGED
@@ -1408,6 +1408,38 @@
1408
1408
  const c = (s.replace(/\[[^\]]*\]|\([^()]*\)/g, '').match(/(?:^|[\s>+~,])[a-z][\w-]*|::[\w-]+/gi) || []).length
1409
1409
  return a * 1e6 + b * 1e3 + c + extra
1410
1410
  }
1411
+ // 像状态的 class(is-active、on、selected……):比「是不是同一种元素」时不算
1412
+ const STATE_CLS = /^(is-|has-)|^(active|on|sel|selected|current|hidden|show|open|disabled|checked|focus|hover)$/
1413
+ /**
1414
+ * 「各屏一起改」能不能写进这条规则:选择器(命中 el 的那一支)最后一节里得有 el 自己的一个 class(cls),
1415
+ * uni:选择器没有逗号并列、页面上这条规则命中的都和 el 是同一种(同标签、去掉状态 class 后 class 一样)——是的话(再经服务端核对各屏)默认各屏一起改;
1416
+ * 「button」「.card a」这种没有 el 的 class 的给 null(只改这一处)
1417
+ */
1418
+ function sharedOf(el, sel) {
1419
+ let cls = ''
1420
+ for (const part of splitList(sel)) {
1421
+ try { if (!el.matches(part)) continue } catch { continue }
1422
+ // 最后一节:顶层(括号、方括号外)最后一个组合符之后
1423
+ let depth = 0
1424
+ let at = 0
1425
+ for (let i = 0; i < part.length; i++) {
1426
+ const ch = part[i]
1427
+ if (ch === '(' || ch === '[') depth++
1428
+ else if (ch === ')' || ch === ']') depth--
1429
+ else if (!depth && (ch === ' ' || ch === '>' || ch === '+' || ch === '~')) at = i + 1
1430
+ }
1431
+ const last = part.slice(at).replace(/\[[^\]]*\]|\((?:[^()]|\([^()]*\))*\)/g, '')
1432
+ for (const m of last.matchAll(/\.(-?[_a-zA-Z][\w-]*)/g)) if (el.classList.contains(m[1]) && !STATE_CLS.test(m[1])) { cls = m[1]; break }
1433
+ if (cls) break
1434
+ }
1435
+ if (!cls) return null
1436
+ const sig = (x) => x.tagName + '|' + [...x.classList].filter((c) => !STATE_CLS.test(c)).sort().join(' ')
1437
+ let hits = []
1438
+ try { hits = [...document.querySelectorAll(sel)] } catch { return null }
1439
+ const me = sig(el)
1440
+ // 逗号并列的(.save-btn, .cancel-btn):别的屏可能是另一种元素,各屏核对只查得到 cls 这一种 → 不默认勾
1441
+ return { cls, cnt: hits.length, uni: splitList(sel).length === 1 && hits.every((x) => sig(x) === me), sig: me.slice(0, 300) }
1442
+ }
1411
1443
  // 面板上的几项各看哪些写法(简写也算)
1412
1444
  const LONGHANDS = {
1413
1445
  'font-size': ['font-size', 'font'], 'font-weight': ['font-weight', 'font'], color: ['color'], background: ['background', 'background-color'],
@@ -1474,8 +1506,12 @@
1474
1506
  for (const k of keys) {
1475
1507
  const b = best[k]
1476
1508
  const inl = (LONGHANDS[k] || [k]).find((L) => el.style.getPropertyValue(L))
1477
- if (inl && (!b || !b.imp || el.style.getPropertyPriority(inl) === 'important')) out[k] = { inline: true, ...(b ? { sel: clip(b.sel, 200), href: b.href, n: b.n } : {}) }
1478
- else if (b) out[k] = { sel: clip(b.sel, 200), href: b.href, n: b.n, ...(b.maybe ? { maybe: true } : {}) }
1509
+ const sh = b && b.sel.length <= 200 && keys === STYLE_KEYS ? sharedOf(el, b.sel) : null
1510
+ const share = sh ? { cls: sh.cls, cnt: sh.cnt, uni: sh.uni, sig: sh.sig } : {}
1511
+ // imp:现在生效的这个值带 !important(行内的、规则的都算):预览和保存都照样带,不然第二次调同一个元素会被规则盖回去
1512
+ const inlImp = !!inl && el.style.getPropertyPriority(inl) === 'important'
1513
+ if (inl && (!b || !b.imp || inlImp)) out[k] = { inline: true, ...(b ? { sel: clip(b.sel, 200), href: b.href, n: b.n, ...share, ...(b.maybe ? { maybe: true } : {}) } : {}), ...(inlImp ? { imp: true } : {}) }
1514
+ else if (b) out[k] = { sel: clip(b.sel, 200), href: b.href, n: b.n, ...share, ...(b.maybe ? { maybe: true } : {}), ...(b.imp ? { imp: true } : {}) }
1479
1515
  }
1480
1516
  return out
1481
1517
  }
@@ -1516,12 +1552,21 @@
1516
1552
  }
1517
1553
 
1518
1554
  /** css:属性 → 值(这次一共改了哪些);每次从原样重来,去掉的那项就回去了 */
1555
+ let styleImpEl = null
1556
+ let styleImp = new Set()
1519
1557
  function styleApply(css) {
1520
1558
  if (!styleEl) return
1521
1559
  styleRevert()
1560
+ // 胜出的规则带 !important(行内没带):预览也带上,不然拖了看不出变化(保存时右侧栏一样带)
1561
+ if (styleImpEl !== styleEl) {
1562
+ styleImpEl = styleEl
1563
+ let r = {}
1564
+ try { r = rulesOf(styleEl) } catch { r = {} }
1565
+ styleImp = new Set(Object.keys(r).filter((k) => r[k] && r[k].imp))
1566
+ }
1522
1567
  for (const [k, v] of Object.entries(css || {})) {
1523
1568
  if (!STYLE_KEYS.includes(k) || typeof v !== 'string' || !v) continue
1524
- styleEl.style.setProperty(k, v)
1569
+ styleEl.style.setProperty(k, v, styleImp.has(k) ? 'important' : '')
1525
1570
  }
1526
1571
  placePin()
1527
1572
  }