dsh-design-studio 1.4.1 → 2.0.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.
Files changed (197) hide show
  1. package/README.en.md +11 -10
  2. package/README.md +17 -16
  3. package/THIRD_PARTY_NOTICES.md +108 -0
  4. package/assets/art/README.md +102 -0
  5. package/assets/art/brand-mark.webp +0 -0
  6. package/assets/art/check-clean.webp +0 -0
  7. package/assets/art/coach-markup.webp +0 -0
  8. package/assets/art/drop-file.webp +0 -0
  9. package/assets/art/empty-components.webp +0 -0
  10. package/assets/art/empty-data.webp +0 -0
  11. package/assets/art/empty-error.webp +0 -0
  12. package/assets/art/empty-frames.webp +0 -0
  13. package/assets/art/empty-history.webp +0 -0
  14. package/assets/art/empty-market.webp +0 -0
  15. package/assets/art/empty-notes.webp +0 -0
  16. package/assets/art/empty-search.webp +0 -0
  17. package/assets/art/empty-tokens.webp +0 -0
  18. package/assets/art/empty-works.webp +0 -0
  19. package/assets/art/guide-icon.webp +0 -0
  20. package/assets/art/kind-app.webp +0 -0
  21. package/assets/art/kind-desktop.webp +0 -0
  22. package/assets/art/kind-diagram.webp +0 -0
  23. package/assets/art/kind-dshplugin.webp +0 -0
  24. package/assets/art/kind-email.webp +0 -0
  25. package/assets/art/kind-embedded.webp +0 -0
  26. package/assets/art/kind-framed.webp +0 -0
  27. package/assets/art/kind-miniprogram.webp +0 -0
  28. package/assets/art/kind-poster.webp +0 -0
  29. package/assets/art/kind-slides.webp +0 -0
  30. package/assets/art/kind-tablet.webp +0 -0
  31. package/assets/art/kind-web.webp +0 -0
  32. package/assets/art/placeholder-inspire-img.webp +0 -0
  33. package/assets/art/wait-creating.webp +0 -0
  34. package/assets/motion/ai-capsule.html +124 -0
  35. package/assets/motion/ai-glow-input.html +112 -0
  36. package/assets/motion/balance-odometer.html +112 -0
  37. package/assets/motion/bottom-sheet.html +149 -0
  38. package/assets/motion/brightness-pill.html +114 -0
  39. package/assets/motion/comet-ring.html +95 -0
  40. package/assets/motion/copy-morph.html +116 -0
  41. package/assets/motion/cube-grid.html +103 -0
  42. package/assets/motion/day-night.html +120 -0
  43. package/assets/motion/dial-knob.html +130 -0
  44. package/assets/motion/dock-magnify.html +118 -0
  45. package/assets/motion/download-ring.html +135 -0
  46. package/assets/motion/expand-card.html +137 -0
  47. package/assets/motion/flip-card.html +100 -0
  48. package/assets/motion/hold-pay.html +137 -0
  49. package/assets/motion/holo-card.html +130 -0
  50. package/assets/motion/keycap.html +92 -0
  51. package/assets/motion/like-jelly.html +88 -0
  52. package/assets/motion/liquid-progress.html +113 -0
  53. package/assets/motion/liquid-segment.html +127 -0
  54. package/assets/motion/live-capsule.html +144 -0
  55. package/assets/motion/marker-highlight.html +94 -0
  56. package/assets/motion/marquee-logos.html +110 -0
  57. package/assets/motion/otp-code.html +111 -0
  58. package/assets/motion/password-eye.html +136 -0
  59. package/assets/motion/ruler-slider.html +140 -0
  60. package/assets/motion/search-expand.html +81 -0
  61. package/assets/motion/send-fly.html +121 -0
  62. package/assets/motion/skeleton-shine.html +124 -0
  63. package/assets/motion/star-rate.html +98 -0
  64. package/assets/motion/success-check.html +114 -0
  65. package/assets/motion/suggest-chips.html +134 -0
  66. package/assets/motion/swipe-row.html +126 -0
  67. package/assets/motion/tabbar-bounce.html +92 -0
  68. package/assets/motion/tactile-controls.html +89 -0
  69. package/assets/motion/text-scramble.html +173 -0
  70. package/assets/motion/toast-stack.html +115 -0
  71. package/assets/motion/token-stream.html +106 -0
  72. package/assets/motion/voice-orb.html +144 -0
  73. package/assets/showcase/alley-noodles-1.webp +0 -0
  74. package/assets/showcase/alley-noodles-2.webp +0 -0
  75. package/assets/showcase/alley-noodles-3.webp +0 -0
  76. package/assets/showcase/autumn-sale-1.webp +0 -0
  77. package/assets/showcase/bold-folio-1.webp +0 -0
  78. package/assets/showcase/bold-folio-2.webp +0 -0
  79. package/assets/showcase/book-club-1.webp +0 -0
  80. package/assets/showcase/book-club-2.webp +0 -0
  81. package/assets/showcase/book-club-3.webp +0 -0
  82. package/assets/showcase/flower-order-1.webp +0 -0
  83. package/assets/showcase/little-painter-1.webp +0 -0
  84. package/assets/showcase/little-painter-2.webp +0 -0
  85. package/assets/showcase/moon-fair-1.webp +0 -0
  86. package/assets/showcase/nail-booking-1.webp +0 -0
  87. package/assets/showcase/nail-booking-2.webp +0 -0
  88. package/assets/showcase/nail-booking-3.webp +0 -0
  89. package/assets/showcase/night-run-1.webp +0 -0
  90. package/assets/showcase/paw-diary-1.webp +0 -0
  91. package/assets/showcase/paw-diary-2.webp +0 -0
  92. package/assets/showcase/paw-diary-3.webp +0 -0
  93. package/assets/showcase/pixel-planet-1.webp +0 -0
  94. package/assets/showcase/pixel-planet-2.webp +0 -0
  95. package/assets/showcase/pixel-planet-3.webp +0 -0
  96. package/assets/showcase/pocket-ledger-1.webp +0 -0
  97. package/assets/showcase/pocket-ledger-2.webp +0 -0
  98. package/assets/showcase/shiftloom-1.webp +0 -0
  99. package/assets/showcase/shiftloom-2.webp +0 -0
  100. package/assets/showcase/slow-breath-1.webp +0 -0
  101. package/assets/showcase/slow-breath-2.webp +0 -0
  102. package/assets/showcase/slow-breath-3.webp +0 -0
  103. package/assets/showcase/slow-trip-1.webp +0 -0
  104. package/assets/showcase/slow-trip-2.webp +0 -0
  105. package/assets/showcase/slow-trip-3.webp +0 -0
  106. package/assets/showcase/slow-weekly-1.webp +0 -0
  107. package/assets/showcase/stay-confirm-1.webp +0 -0
  108. package/assets/showcase/stove-recipes-1.webp +0 -0
  109. package/assets/showcase/stove-recipes-2.webp +0 -0
  110. package/assets/showcase/strobewatch-1.webp +0 -0
  111. package/assets/showcase/strobewatch-2.webp +0 -0
  112. package/assets/showcase/tapeworks-1.webp +0 -0
  113. package/assets/showcase/tapeworks-2.webp +0 -0
  114. package/assets/showcase/tea-brand-pitch-1.webp +0 -0
  115. package/assets/showcase/tea-brand-pitch-2.webp +0 -0
  116. package/assets/showcase/tea-brand-pitch-3.webp +0 -0
  117. package/assets/showcase/time-bookshop-1.webp +0 -0
  118. package/assets/showcase/time-bookshop-2.webp +0 -0
  119. package/assets/showcase/water-journey-1.webp +0 -0
  120. package/assets/showcase/water-journey-2.webp +0 -0
  121. package/assets/showcase/water-journey-3.webp +0 -0
  122. package/assets/showcase/weekend-go-1.webp +0 -0
  123. package/assets/showcase/weekend-go-2.webp +0 -0
  124. package/assets/showcase/weekend-go-3.webp +0 -0
  125. package/assets/showcase/winter-soup-1.webp +0 -0
  126. package/assets/showcase/year-review-1.webp +0 -0
  127. package/assets/showcase/year-review-2.webp +0 -0
  128. package/assets/showcase/year-review-3.webp +0 -0
  129. package/lib/annotations.js +1 -1
  130. package/lib/browser.js +3 -1
  131. package/lib/bundle.js +8 -3
  132. package/lib/canvthumb.js +9 -6
  133. package/lib/client.js +7623 -2788
  134. package/lib/components.js +4 -2
  135. package/lib/core.js +763 -133
  136. package/lib/design-page-settings.js +48 -0
  137. package/lib/design-scope.js +36 -0
  138. package/lib/design-transactions.js +259 -0
  139. package/lib/drop-folder.js +25 -0
  140. package/lib/edits.js +125 -8
  141. package/lib/embedded/lvgl_shot.c +133 -0
  142. package/lib/embedded/qml_shot.py +66 -0
  143. package/lib/embedded-shot.js +400 -0
  144. package/lib/embedded-trust.js +76 -0
  145. package/lib/fonts.js +30 -21
  146. package/lib/frames.js +23 -23
  147. package/lib/gallery/css.js +9 -2
  148. package/lib/gallery/market-routes.js +23 -7
  149. package/lib/gallery/pack.js +25 -8
  150. package/lib/gallery/policy.js +6 -4
  151. package/lib/gallery/routes.js +255 -83
  152. package/lib/gallery/submit.js +285 -57
  153. package/lib/gallery/use.js +13 -4
  154. package/lib/handoff-embedded.js +1182 -0
  155. package/lib/handoff.js +212 -71
  156. package/lib/history.js +393 -43
  157. package/lib/htmlpack.js +35 -14
  158. package/lib/impl.js +3 -0
  159. package/lib/index.js +662 -137
  160. package/lib/inspire.js +73 -26
  161. package/lib/kinds.js +11 -2
  162. package/lib/look.js +45 -25
  163. package/lib/mock.js +41 -4
  164. package/lib/motion.js +90 -0
  165. package/lib/page-settings.js +103 -0
  166. package/lib/picker.js +348 -70
  167. package/lib/rules.js +85 -0
  168. package/lib/serve.js +154 -15
  169. package/lib/showcase.json +22 -0
  170. package/lib/styles.js +16 -7
  171. package/lib/system.js +19 -8
  172. package/lib/tool.js +2 -1
  173. package/lib/tweaks.js +146 -9
  174. package/lib/works.js +151 -19
  175. package/locale/annotations/en.json +2 -2
  176. package/locale/annotations/zh.json +2 -2
  177. package/locale/auto/en.json +1 -1
  178. package/locale/auto/zh.json +1 -1
  179. package/locale/en.json +1 -1
  180. package/locale/offline/en.json +1 -1
  181. package/locale/offline/zh.json +2 -2
  182. package/locale/tool/zh.json +1 -1
  183. package/locale/zh.json +1 -1
  184. package/package.json +3 -2
  185. package/skills/ui-design/SKILL.md +59 -47
  186. package/skills/ui-design/frames/dsh/frame.json +1 -1
  187. package/skills/ui-design/references/app.md +29 -2
  188. package/skills/ui-design/references/components.md +1 -1
  189. package/skills/ui-design/references/desktop.md +1 -1
  190. package/skills/ui-design/references/dshplugin.md +12 -12
  191. package/skills/ui-design/references/embedded.md +40 -0
  192. package/skills/ui-design/references/frames.md +20 -20
  193. package/skills/ui-design/references/miniprogram.md +2 -2
  194. package/skills/ui-design/references/mock.md +16 -0
  195. package/skills/ui-design/references/poster.md +2 -1
  196. package/skills/ui-design/references/tweaks.md +17 -0
  197. package/skills/ui-design/tokens.css +19 -5
package/lib/history.js CHANGED
@@ -8,9 +8,21 @@
8
8
  * 跳过 node_modules、.git、隐藏目录、exports/(导出的图片)和 refs/(参考图)。目录太大(多半是整个项目)就不存。
9
9
  */
10
10
  import fs from 'node:fs'
11
+ export { designWriteScope } from './design-transactions.js'
12
+
11
13
  import path from 'node:path'
12
14
  import crypto from 'node:crypto'
15
+ import { bundle, dataAssets, srcsetParts } from './bundle.js'
16
+ import { tokenize } from './gallery/html.js'
17
+ import { scanCss } from './gallery/css.js'
18
+ import { expandPreview } from './comp-io.js'
19
+ import { designOf, originalOf, metaOfFile, parseMeta } from './look.js'
20
+ import { portablePages } from './page-settings.js'
21
+ import { PAGE_SETTINGS, SIDE_PAGE_SETTINGS, pageSettingsBytes, readPageSettingsBytes } from './design-page-settings.js'
22
+ import { atomicWrite, readItem, studioError } from './design-transactions.js'
13
23
  import { isLibFontRel } from './fonts.js'
24
+ import { versionAction } from './edits.js'
25
+ import { MOCK_FILE, mockOfBuf } from './mock.js'
14
26
 
15
27
  const KEEP_EXT = /\.(html?|css|m?js|json|svg|txt|md|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf)$/i
16
28
  const SKIP_DIR = /^(node_modules|\.git|\.next|\.cache|\.turbo|dist|build|exports|refs|handoff)$|^\./
@@ -22,6 +34,7 @@ const MAX_DEPTH = 3
22
34
  const MAX_VERSIONS = 40
23
35
 
24
36
  const HASH = /^[0-9a-f]{40}$/
37
+ const sharedFiles = new Set(['design.json', 'system.json', 'tokens.css', 'tweaks.json', MOCK_FILE, 'rules.md', 'annotations.json'])
25
38
 
26
39
  const sha1 = (buf) => crypto.createHash('sha1').update(buf).digest('hex')
27
40
 
@@ -75,6 +88,142 @@ export function collect(root) {
75
88
  return walk(root, '', 0) ? out : null
76
89
  }
77
90
 
91
+ /** Read only dependencies reachable from the opened HTML. They are never write targets. */
92
+ export function fileDependencies(root, entry) {
93
+ const found = {}
94
+ let total = 0
95
+ const read = rel => {
96
+ if (!rel || !KEEP_EXT.test(rel) || rel.split('/').some(part => SKIP_DIR.test(part))) return null
97
+ if (/\.html?$/i.test(rel) && rel !== entry && !rel.startsWith('components/')) return null
98
+ const abs = path.join(root, rel)
99
+ let item
100
+ try { item = readItem(root, rel) } catch { return null }
101
+ if (!item.data || item.data.length > MAX_FILE) return null
102
+ if (!Object.hasOwn(found, rel)) {
103
+ if (Object.keys(found).length >= MAX_FILES || total + item.data.length > MAX_TOTAL) return null
104
+ total += item.data.length
105
+ found[rel] = abs
106
+ }
107
+ return item.data
108
+ }
109
+ const source = read(entry)
110
+ if (source) {
111
+ const expanded = expandPreview(source.toString('utf8'), read, entry).html
112
+ bundle(expanded, { key: entry, read, base: 'http://localhost/' + encodeURIComponent(entry) })
113
+ if (/\b(?:data-mock(?:-|=)|mock\.|\$mock\b)/i.test(expanded)) read('mock.json')
114
+ }
115
+ return found
116
+ }
117
+
118
+ // Scan literal module specifiers only. Skip comments and strings as whole tokens.
119
+ function moduleRefs(source, reference) {
120
+ const lex = /\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|[\w$]+|[^\s]/g
121
+ const regex = /\/(?:\\[^\n\r]|\[(?:\\[^\n\r]|[^\]\\\n\r])*\]|[^/\[\\\n\r])+\/[a-z]*/y
122
+ const tokens = []
123
+ for (let match; (match = lex.exec(source));) {
124
+ const [token] = match
125
+ if (/^\/[/\*]/.test(token)) continue
126
+ if (token === '/' && /^(?:|[=(\[{,:;!?&|]|return|throw|case|yield)$/.test(tokens.at(-1) || '')) {
127
+ regex.lastIndex = match.index
128
+ const literal = regex.exec(source)
129
+ if (literal) { tokens.push(literal[0]); lex.lastIndex = regex.lastIndex; continue }
130
+ }
131
+ tokens.push(token)
132
+ }
133
+ const local = token => /^["']\.{0,2}\/(?!\/)/.test(token || '')
134
+ for (let i = 0; i < tokens.length; i++) {
135
+ const token = tokens[i], next = tokens[i + 1]
136
+ if ((token !== 'import' && token !== 'export') || tokens[i - 1] === '.') continue
137
+ if (token === 'import' && (next === '(' || /^["']/.test(next || ''))) {
138
+ const spec = next === '(' ? tokens[i + 2] : next
139
+ if (local(spec) && (next !== '(' || [')', ','].includes(tokens[i + 3]))) reference(spec.slice(1, -1))
140
+ continue
141
+ }
142
+ if (token === 'export' && next !== '*' && next !== '{') continue
143
+ for (let j = i + 1; j < tokens.length && /^[\w$*{},]+$/.test(tokens[j]); j++) {
144
+ if (tokens[j] !== 'from' || !/^["']/.test(tokens[j + 1] || '')) continue
145
+ if (local(tokens[j + 1])) reference(tokens[j + 1].slice(1, -1))
146
+ break
147
+ }
148
+ }
149
+ }
150
+
151
+ // Derive write ownership using only the archived bytes.
152
+ function archivedDependencies(files, screens, missing) {
153
+ const owned = new Set()
154
+ const visited = new Set()
155
+ const expanding = new Set()
156
+ const origin = 'https://design.invalid'
157
+ const fileUrl = key => new URL('/' + key.split('/').map(encodeURIComponent).join('/'), origin)
158
+ function visit(key, base = fileUrl(key)) {
159
+ if (!files.has(key)) { missing.add(key); return }
160
+ owned.add(key)
161
+ const id = key + '|' + base.href
162
+ if (visited.has(id)) return
163
+ visited.add(id)
164
+ const reference = raw => {
165
+ if (!raw || /^\s*(?:#|\?|\/\/|[a-z][\w+.-]*:)/i.test(raw)) return
166
+ let url, rel
167
+ try { url = new URL(raw, base); rel = decodeURIComponent(url.pathname.slice(1)) } catch { return }
168
+ if (url.origin !== origin || !rel || rel.split('/').some(part => !part || part === '..' || part === '.')) return
169
+ if (!/\.html?$/i.test(rel)) visit(rel)
170
+ }
171
+ const css = source => { for (const { url } of scanCss(source, { importUrls: true }).refs) reference(url) }
172
+ if (/\.css$/i.test(key)) { css(files.get(key).toString('utf8')); return }
173
+ if (/\.m?js$/i.test(key)) { moduleRefs(files.get(key).toString('utf8'), reference); return }
174
+ if (!/\.(?:html?|svg)$/i.test(key)) return
175
+ const tokens = tokenize(files.get(key).toString('utf8'))
176
+ const baseHref = tokens.find(t => t.type === 'tag' && t.tag.name === 'base' && t.tag.attrs.some(a => a.name === 'href'))
177
+ if (baseHref) {
178
+ try { base = new URL(baseHref.tag.attrs.find(a => a.name === 'href').value, base) } catch { return }
179
+ }
180
+ let inlineModule = false
181
+ for (const token of tokens) {
182
+ if (token.type === 'text' && token.raw === 'style') { css(token.text); continue }
183
+ if (token.type === 'text' && token.raw === 'script' && inlineModule) { moduleRefs(token.text, reference); continue }
184
+ if (token.type !== 'tag') continue
185
+ const { name, attrs } = token.tag
186
+ const a = Object.fromEntries(attrs.filter(a => !a.dup && !a.unknown.length).map(a => [a.name, a.value]))
187
+ if (name === 'script') inlineModule = !a.src && a.type?.trim().toLowerCase() === 'module'
188
+ if (a.style) css(a.style)
189
+ if (name === 'link' && (a.rel || '').split(/\s+/).some(r => /^(?:stylesheet|icon|preload|modulepreload|manifest)$/i.test(r))) reference(a.href)
190
+ if (['img', 'script', 'source', 'audio', 'video', 'track', 'embed'].includes(name) || (name === 'input' && a.type?.toLowerCase() === 'image')) reference(a.src)
191
+ if (name === 'img' || name === 'source') for (const [url] of srcsetParts(a.srcset || '')) reference(url)
192
+ if (name === 'video') reference(a.poster)
193
+ if (name === 'image' || name === 'use') reference(a.href || a['xlink:href'])
194
+ if (name === 'object') reference(a.data)
195
+ if (/^c-[a-z][\w-]*$/.test(name)) {
196
+ const component = 'components/' + name.slice(2) + '.html'
197
+ if (files.has(component) && !expanding.has(component)) {
198
+ expanding.add(component)
199
+ visit(component, base)
200
+ expanding.delete(component)
201
+ }
202
+ }
203
+ }
204
+ }
205
+ for (const key of screens) visit(key)
206
+ const mock = mockOfBuf(files.get(MOCK_FILE))
207
+ if (mock && !mock.err) dataAssets(mock.data, key => { visit(key); return null })
208
+ return owned
209
+ }
210
+
211
+ export function historicalViewports(screens, settings, fileOf, defaults = {}, legacyViewport = {}) {
212
+ return Object.fromEntries(screens.map(key => {
213
+ const row = settings?.screens?.[key]
214
+ const file = fileOf(key)
215
+ const meta = file ? metaOfFile(file) : ''
216
+ const declared = parseMeta(meta)
217
+ const result = row?.followSource ? originalOf(defaults, meta)
218
+ : row?.current ? designOf(row.current, () => meta)
219
+ : row?.original ? designOf(row.original, () => meta)
220
+ : designOf(declared.kind || declared.size ? defaults : { ...legacyViewport, ...defaults }, () => meta)
221
+ const [w, h] = result.size
222
+ const os = /\b(?:windows|win(?:10|11)?)\b/i.test(meta) ? 'win' : defaults.os || ''
223
+ return [key, { kind: result.kind, w, h, os, ...(result.auto ? { auto: true } : {}), ...(defaults.view ? { view: defaults.view } : {}) }]
224
+ }))
225
+ }
226
+
78
227
  /** 两版之间改了哪些文件(新增、改了、删了) */
79
228
  export function diffFiles(a = {}, b = {}) {
80
229
  const changed = []
@@ -87,9 +236,16 @@ export function diffFiles(a = {}, b = {}) {
87
236
  * @param opts.base 存放目录
88
237
  * @param opts.now 取时间(测试用)
89
238
  */
90
- export function createHistory({ base, now = Date.now, log = () => {} }) {
91
- const dirOf = (root) => path.join(base, sha1(path.resolve(root)).slice(0, 16))
92
- const sigs = new Map() // root → 上次存的时候各文件的大小 + 修改时间(没变就不用再读一遍算哈希)
239
+ export function createHistory({ base, now = Date.now, log = () => {}, findDesign = () => null }) {
240
+ const legacyDir = root => path.join(base, sha1(path.resolve(root)).slice(0, 16))
241
+ const rootOf = ref => typeof ref === 'string' ? ref : ref.root
242
+ const dirOf = ref => {
243
+ const designId = (typeof ref === 'string' ? findDesign(ref) : ref.designId) || ''
244
+ if (!/^(?:file|directory)-[0-9a-f]{16}$/.test(designId)) return legacyDir(rootOf(ref))
245
+ const stable = path.join(base, designId.startsWith('directory-') ? designId.slice(10) : designId)
246
+ return stable
247
+ }
248
+ const skipKey = ref => dirOf(ref)
93
249
  const skips = new Map() // root → { at }:最近一次因为目录太大没存成(存成了 / 没改动就清掉),版本面板据此提示
94
250
 
95
251
  function load(root) {
@@ -107,6 +263,46 @@ export function createHistory({ base, now = Date.now, log = () => {} }) {
107
263
  fs.renameSync(tmp, path.join(dir, 'index.json'))
108
264
  }
109
265
 
266
+ function migrateLegacy(root, ref) {
267
+ const source = legacyDir(root), destination = dirOf(ref)
268
+ if (source === destination) return
269
+ try {
270
+ const read = dir => {
271
+ try {
272
+ const rows = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8'))
273
+ if (!Array.isArray(rows)) throw Error('版本索引格式有误')
274
+ return rows
275
+ } catch (e) { if (e.code === 'ENOENT') return []; throw e }
276
+ }
277
+ const legacySource = path.basename(source)
278
+ const legacy = read(source).filter(row => !row.screens)
279
+ if (!legacy.length) return
280
+ const current = read(destination)
281
+ const imported = new Set(current.filter(v => v.legacySource === legacySource).map(v => v.legacyNumber))
282
+ const pending = legacy.filter(v => !imported.has(v.n))
283
+ if (!pending.length) return
284
+ const objects = path.join(destination, 'objects')
285
+ fs.mkdirSync(objects, { recursive: true })
286
+ let n = current.at(-1)?.n || 0
287
+ const copied = new Set()
288
+ for (const v of pending) {
289
+ for (const key of Object.keys(v.files)) {
290
+ const hash = hashOf(v, key)
291
+ if (!hash) throw Error('旧版本文件索引有误:' + key)
292
+ if (copied.has(hash)) continue
293
+ const bytes = fs.readFileSync(path.join(source, 'objects', hash))
294
+ if (sha1(bytes) !== hash) throw Error('旧版本文件校验失败:' + key)
295
+ const file = path.join(objects, hash)
296
+ if (!fs.existsSync(file) || !fs.readFileSync(file).equals(bytes)) atomicWrite(file, bytes)
297
+ copied.add(hash)
298
+ }
299
+ n = Math.max(n + 1, v.n)
300
+ current.push({ ...v, n, legacySource, legacyNumber: v.n })
301
+ }
302
+ save(ref, current)
303
+ } catch (e) { log(e) }
304
+ }
305
+
110
306
  /** 旧版本删掉后,没人用的文件内容一起清掉 */
111
307
  function gc(root, list) {
112
308
  const keep = new Set()
@@ -121,9 +317,9 @@ export function createHistory({ base, now = Date.now, log = () => {} }) {
121
317
  * 存一版:和最近一版一模一样就不存。
122
318
  * @returns 新的一版 { n, at, label, files } / null(没变、不像设计目录、出错)
123
319
  */
124
- function snapshot(root, label = '', by = '') {
320
+ function snapshot(root, label = '', by = '', scope) {
125
321
  try {
126
- return take(root, label, false, by)
322
+ return take(root, label, false, by, scope)
127
323
  } catch (e) {
128
324
  log(e)
129
325
  return null
@@ -131,63 +327,211 @@ export function createHistory({ base, now = Date.now, log = () => {} }) {
131
327
  }
132
328
 
133
329
  /** snapshot 的本体:出错直接抛;strict 时目录太大(存不下)也抛 */
134
- function take(root, label, strict, by = '') {
135
- const found = collect(root)
136
- if (!found) skips.set(path.resolve(root), { at: now() })
330
+ function take(ref, label, strict, by = '', scope) {
331
+ const root = rootOf(ref)
332
+ const found = scope?.scope === 'file' ? fileDependencies(root, scope.entry) : collect(root)
333
+ if (!found) skips.set(skipKey(ref), { at: now() })
137
334
  if (!found && strict) throw new Error('目录太大(多半是整个项目),存不了现在的样子')
138
- if (!found || !Object.keys(found).length) return null
139
- skips.delete(path.resolve(root))
140
- let sig = ''
141
- for (const [rel, abs] of Object.entries(found)) {
142
- try { const st = fs.statSync(abs); sig += `${rel}:${st.size}:${st.mtimeMs}\n` } catch { /* 刚删 */ }
335
+ if (!found || !scope && !Object.keys(found).length) return null
336
+ skips.delete(skipKey(ref))
337
+ if (scope?.scope === 'directory') {
338
+ for (const key of Object.keys(found)) {
339
+ if (/^[^/]+\.html?$/i.test(key) && !scope.pages.includes(key)) delete found[key]
340
+ }
341
+ if (scope.settingsPresent && scope.settingsFile === SIDE_PAGE_SETTINGS) found[SIDE_PAGE_SETTINGS] = path.join(root, SIDE_PAGE_SETTINGS)
143
342
  }
144
- if (sigs.get(root) === sig && load(root).length) return null
145
- const objDir = path.join(dirOf(root), 'objects')
343
+ const objDir = path.join(dirOf(ref), 'objects')
146
344
  fs.mkdirSync(objDir, { recursive: true })
147
345
  const files = {}
148
346
  for (const [rel, abs] of Object.entries(found)) {
149
347
  let buf
150
- try { buf = fs.readFileSync(abs) } catch { continue }
348
+ try { buf = fs.readFileSync(abs) } catch (e) { if (strict) throw e; continue }
151
349
  const h = sha1(buf)
152
350
  const obj = path.join(objDir, h)
153
- if (!fs.existsSync(obj)) fs.writeFileSync(obj, buf)
351
+ if (!fs.existsSync(obj)) atomicWrite(obj, buf)
154
352
  files[rel] = h
155
353
  }
156
- const list = load(root)
354
+ const list = load(ref)
157
355
  const last = list[list.length - 1]
158
- if (last && !diffFiles(last.files, files).length) { sigs.set(root, sig); return null }
356
+ const metadata = scope ? {
357
+ screens: scope.pages,
358
+ ...(scope.pages.some(key => !Object.hasOwn(files, key)) ? { incomplete: scope.pages.filter(key => !Object.hasOwn(files, key)) } : {}),
359
+ owned: scope.owned.filter(key => Object.hasOwn(files, key)),
360
+ managed: Object.keys(files).filter(key => sharedFiles.has(key) || scope.managed?.includes(key)),
361
+ settings: portablePages(scope.settings, scope.pages),
362
+ } : {}
363
+ if (scope) {
364
+ metadata.viewports = historicalViewports(metadata.screens, metadata.settings, key => found[key], scope)
365
+ if (Object.hasOwn(metadata.settings, 'devices')) metadata.devices = metadata.settings.devices
366
+ if (scope.scope === 'directory') metadata.settingsFile = scope.settingsPresent ? scope.settingsFile : null
367
+ if (scope.display) metadata.display = scope.display
368
+ }
369
+ const prev = last && Object.fromEntries(Object.keys(metadata).map(key => [key, last[key]]))
370
+ if (last && !diffFiles(last.files, files).length && JSON.stringify(prev) === JSON.stringify(metadata)) return null
159
371
  // by:谁改出来的这一版(ai 模型这一轮改完、me 手调写回、pre 手调写回之前;空的是这轮开始前 / 回退前)
160
- const v = { n: last ? last.n + 1 : 1, at: now(), label: String(label || '').slice(0, 80), ...(by ? { by: String(by) } : {}), files }
372
+ const v = { n: last ? last.n + 1 : 1, at: now(), label: String(label || '').slice(0, 80), ...(by ? { by: String(by) } : {}), files, ...metadata }
161
373
  list.push(v)
162
- const cut = list.length > MAX_VERSIONS ? list.splice(0, list.length - MAX_VERSIONS) : []
163
- save(root, list)
164
- sigs.set(root, sig) // 真存上了才记(存到一半出错,下次还得重存)
165
- if (cut.length) { try { gc(root, list) } catch (e) { log(e) } }
374
+ // Imported alias archives retain their own quota, even if the destination is already full.
375
+ const regular = list.filter(v => !v.legacySource)
376
+ const cut = new Set(regular.slice(0, Math.max(0, regular.length - MAX_VERSIONS)))
377
+ const retained = cut.size ? list.filter(v => !cut.has(v)) : list
378
+ save(ref, retained)
379
+ if (cut.size) { try { gc(ref, retained) } catch (e) { log(e) } }
166
380
  return v
167
381
  }
168
382
 
169
- /** 给右侧栏的版本列表:新的在前,带改了哪些文件(最早的一版带一共几个文件) */
170
- function list(root) {
171
- const all = load(root)
172
- return all.map((v, i) => ({
173
- n: v.n,
174
- at: v.at,
175
- label: v.label,
176
- by: v.by || '',
177
- changed: i ? diffFiles(all[i - 1].files, v.files) : [], // 最早的一版没得比
178
- first: !i,
179
- count: Object.keys(v.files).length,
180
- screens: Object.keys(v.files).filter((f) => /^[^/]+\.html?$/i.test(f)),
181
- })).reverse()
383
+ function verifyBackup(ref, paths) {
384
+ const root = rootOf(ref)
385
+ try {
386
+ const originals = paths.map(rel => {
387
+ if (fs.statSync(path.join(root, rel)).size > MAX_FILE) return null
388
+ const current = fs.readFileSync(path.join(root, rel))
389
+ const hash = sha1(current)
390
+ const archived = fs.readFileSync(path.join(dirOf(ref), 'objects', hash))
391
+ return archived.equals(current) ? { rel, hash } : null
392
+ })
393
+ if (!originals.length) return true
394
+ return originals.every(Boolean) && load(ref).some(v => originals.every(({ rel, hash }) => hashOf(v, rel) === hash))
395
+ } catch { return false }
182
396
  }
183
397
 
184
- /** 某一版里某个文件存在哪(给预览服务器读);没有给 null */
185
- function fileOf(root, n, rel) {
186
- const v = load(root).find((x) => x && x.n === Number(n))
398
+ const screensOf = version => version.screens || Object.keys(version.files).filter(f => /^[^/]+\.html?$/i.test(f))
399
+
400
+ function find(ref, n, at) {
401
+ return load(ref).find(v => v && v.n === Number(n) && (at === undefined || Number(v.at) === Number(at)))
402
+ }
403
+
404
+ function fileOf(ref, n, rel) {
405
+ const v = find(ref, n)
187
406
  if (!v) return null
188
407
  const key = String(rel || '').replace(/^\/+/, '') || 'index.html'
189
408
  const h = hashOf(v, key) || (key.endsWith('/') ? hashOf(v, key + 'index.html') : null)
190
- return h ? path.join(dirOf(root), 'objects', h) : null
409
+ if (!h) return null
410
+ const file = path.join(dirOf(ref), 'objects', h)
411
+ try { return sha1(fs.readFileSync(file)) === h ? file : null } catch { return null }
412
+ }
413
+
414
+ function archivedSettingsFile(v, bytes) {
415
+ if (Object.hasOwn(v, 'settingsFile')) return v.settingsFile
416
+ if (v.settingsPresent && readPageSettingsBytes(bytes)) return PAGE_SETTINGS
417
+ return null // 1.5.0 never wrote a page settings file.
418
+ }
419
+
420
+ function legacyProjectSettings(ref, bytes) {
421
+ const hash = sha1(bytes)
422
+ const all = load(ref)
423
+ const matching = all.filter(v => hashOf(v, PAGE_SETTINGS) === hash)
424
+ if (matching.length) return matching.some(v => archivedSettingsFile(v, bytes) !== PAGE_SETTINGS)
425
+ return all.some(v => !v.screens && hashOf(v, PAGE_SETTINGS))
426
+ }
427
+
428
+ function list(ref) {
429
+ const all = load(ref)
430
+ return all.map((v, i) => {
431
+ const screens = screensOf(v)
432
+ const settings = v.settings || { screens: {} }
433
+ const changed = i ? diffFiles(all[i - 1].files, v.files) : []
434
+ if (i && JSON.stringify(all[i - 1].settings || { screens: {} }) !== JSON.stringify(settings) && !changed.some(key => key === PAGE_SETTINGS || key === SIDE_PAGE_SETTINGS)) changed.push(PAGE_SETTINGS)
435
+ return {
436
+ n: v.n, at: v.at, label: v.label, ...versionAction(v), by: v.by || '', changed, first: !i,
437
+ count: Object.keys(v.files).length, screens,
438
+ viewports: v.viewports || historicalViewports(screens, settings, key => fileOf(ref, v.n, key), {}, ref.legacyViewport),
439
+ devices: v.devices ?? settings.devices ?? null, settings, ...(v.display ? { display: v.display } : {}),
440
+ }
441
+ }).reverse()
442
+ }
443
+
444
+ function contents(ref, version) {
445
+ if (version.incomplete?.length) throw studioError('backup', '第 ' + version.n + ' 版缺少文件:' + version.incomplete.join('、'))
446
+ return new Map(Object.keys(version.files).map(key => {
447
+ const file = fileOf(ref, version.n, key)
448
+ if (!file) throw studioError('backup', `第 ${version.n} 版的文件不全(${key})`)
449
+ return [key, fs.readFileSync(file)]
450
+ }))
451
+ }
452
+
453
+ function versionHtmlHashes(ref, version) {
454
+ return screensOf(version).map(key => {
455
+ const file = fileOf(ref, version.n, key)
456
+ return file && crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
457
+ }).filter(Boolean)
458
+ }
459
+
460
+ function plan(ref, version, scope) {
461
+ const files = contents(ref, version)
462
+ const archivedSettings = archivedSettingsFile(version, files.get(PAGE_SETTINGS))
463
+ const projectSettingsFile = files.has(PAGE_SETTINGS) && archivedSettings !== PAGE_SETTINGS
464
+ const archivedScreens = screensOf(version)
465
+ const wanted = new Set(scope.scope === 'file' ? scope.entry ? [scope.entry] : [] : archivedScreens)
466
+ const owned = new Set(scope.owned)
467
+ const beforeScreens = new Set(scope.pages)
468
+ const unknown = scope.pages.filter(key => !wanted.has(key) && !owned.has(key))
469
+ if (unknown.length) throw studioError('scope', '无法确认这些文件属于此设计:' + unknown.join('、'))
470
+ const skipped = new Set(), missing = new Set()
471
+ const dependencies = scope.scope === 'directory' ? archivedDependencies(files, wanted, missing) : new Set()
472
+ const writes = new Map()
473
+ const settingsFiles = []
474
+ const overwrite = [], add = [], archive = []
475
+ const hashes = []
476
+ const root = rootOf(ref)
477
+ function compare(key, data) {
478
+ const current = readItem(root, key)
479
+ const present = current.data !== null
480
+ if (data ? current.data?.equals(data) : !present) return
481
+ if (present && current.data.length > MAX_FILE && !isLibFontRel(key)) throw studioError('backup', key + ' 超过 2MB,无法备份')
482
+ if (present && wanted.has(key) && !owned.has(key) && !version.owned?.includes(key) && !scope.initial.includes(key)) throw studioError('scope', '无法确认文件归属:' + key)
483
+ writes.set(key, data)
484
+ hashes.push([key, current.hash, data ? sha1(data) : null])
485
+ if (!data) archive.push(key)
486
+ else (present ? overwrite : add).push(key)
487
+ }
488
+ function noteSkipped(key, data) {
489
+ try { if (!readItem(root, key).data?.equals(data)) skipped.add(key) } catch { skipped.add(key) }
490
+ }
491
+ for (const [key, data] of files) {
492
+ if (key === archivedSettings) continue
493
+ if (scope.scope === 'file') {
494
+ if (key === archivedScreens[0] && scope.entry) compare(scope.entry, data)
495
+ else noteSkipped(key, data)
496
+ continue
497
+ }
498
+ if (/^[^/]+\.html?$/i.test(key)) {
499
+ if (!wanted.has(key)) continue
500
+ } else if (key !== PAGE_SETTINGS && !dependencies.has(key) && !sharedFiles.has(key) && !version.managed?.includes(key) && !scope.managed?.includes(key)) {
501
+ // An old folder snapshot can include neighbouring work. Report only differences.
502
+ noteSkipped(key, data)
503
+ continue
504
+ }
505
+ compare(key, data)
506
+ }
507
+ for (const key of owned) if (beforeScreens.has(key) && !wanted.has(key)) compare(key, null)
508
+ const rawSettings = version.settings || { screens: {} }
509
+ const settings = scope.scope === 'file' && archivedScreens[0] !== scope.entry
510
+ ? { ...rawSettings, screens: rawSettings.screens?.[archivedScreens[0]] && scope.entry ? { [scope.entry]: rawSettings.screens[archivedScreens[0]] } : {} }
511
+ : rawSettings
512
+ if (scope.scope === 'directory') {
513
+ const current = scope.settingsPresent ? scope.settingsFile : null
514
+ const compareSettings = (key, data) => {
515
+ compare(key, data)
516
+ if (writes.has(key)) settingsFiles.push(key)
517
+ }
518
+ if (projectSettingsFile && !archivedSettings && !version.settings) {
519
+ // A project file from 1.5.0 replaces only its own path. Keep any newer plugin settings.
520
+ if (current === PAGE_SETTINGS) compareSettings(SIDE_PAGE_SETTINGS, pageSettingsBytes(scope.settings))
521
+ } else {
522
+ const next = archivedSettings && (projectSettingsFile || scope.settingsFile === SIDE_PAGE_SETTINGS ? SIDE_PAGE_SETTINGS : PAGE_SETTINGS)
523
+ if (current && current !== next && !(projectSettingsFile && current === PAGE_SETTINGS)) compareSettings(current, null)
524
+ if (next) compareSettings(next, pageSettingsBytes(settings))
525
+ }
526
+ }
527
+ return { writes, overwrite, add, archive, settingsFiles, skipped: [...skipped].sort(), missing: [...missing].sort(), hashes, settings, screens: [...wanted], display: version.display || null }
528
+ }
529
+
530
+ function validateMove(ref, to, scope) {
531
+ const source = dirOf(ref)
532
+ const destination = scope === 'file' ? dirOf({ root: path.dirname(to), designId: 'file-' + sha1(path.resolve(to)).slice(0, 16) }) : legacyDir(to)
533
+ if (source !== destination && fs.existsSync(path.join(destination, 'index.json'))) throw studioError('workDestinationConflict', '所选目录已有版本记录,请重新选择。')
534
+ for (const version of load(ref)) contents(ref, version)
191
535
  }
192
536
 
193
537
  /**
@@ -250,6 +594,12 @@ export function createHistory({ base, now = Date.now, log = () => {} }) {
250
594
  }
251
595
 
252
596
  /** 最近一次没存成(目录超过 300 个文件 / 30 MB):{ at, files, total };没有给 null */
253
- const skipped = (root) => { const s = skips.get(path.resolve(root)); return s ? { ...s, files: MAX_FILES, mb: MAX_TOTAL / 1024 / 1024 } : null }
254
- return { snapshot, list, fileOf, restore, dirOf, skipped }
597
+ const skipped = (root) => { const s = skips.get(skipKey(root)); return s ? { ...s, files: MAX_FILES, mb: MAX_TOTAL / 1024 / 1024 } : null }
598
+ function legacyEntry(root, entry) {
599
+ try {
600
+ const versions = JSON.parse(fs.readFileSync(path.join(legacyDir(root), 'index.json'), 'utf8'))
601
+ return versions.some(v => !v.screens && hashOf(v, entry))
602
+ } catch { return false }
603
+ }
604
+ return { snapshot, take, list, find, legacyEntry, legacyProjectSettings, migrateLegacy, latest: ref => load(ref).at(-1), fileOf, contents, versionHtmlHashes, plan, validateMove, restore, dirOf, skipped, verifyBackup }
255
605
  }