dsh-design-studio 0.16.1 → 0.18.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.
@@ -9,6 +9,8 @@
9
9
  * GET inspire 灵感(参考图、网址、我的风格)
10
10
  * POST inspire { op, … } addImage / addUrl / addStyle / addMarket / remove
11
11
  * GET inspimg ?id= 灵感里的图片
12
+ * GET/POST ghauth { op } 一键投稿:连 GitHub(设备授权)、断开
13
+ * POST submit { path } 一键投稿:把刚打好的分享包投上去(见 submit.js)
12
14
  */
13
15
 
14
16
  import crypto from 'node:crypto'
@@ -23,6 +25,7 @@ import { PERSONAL_CODES } from './policy.js'
23
25
  import { readZip, ZipError } from './zip.js'
24
26
  import { renderPack } from './render.js'
25
27
  import { preparePack, installPack, baseFor, slugOf, UseError } from './use.js'
28
+ import { createGitHub, GhError, packPrint } from './submit.js'
26
29
 
27
30
  const THUMB_DIR = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'works', 'thumbs')
28
31
  const MAX_ZIP_BODY = 12 * 1024 * 1024 // base64 的 8MB zip
@@ -102,8 +105,10 @@ export function describeWork(w) {
102
105
  return { ...base, title: manifestTitle(dir) || product || w.title || path.basename(dir), kind, screens: screens.length, first: screens[0] || '', updated: Math.round(updated || w.updated || w.seen || 0), thumb: sig ? crypto.createHash('sha1').update(sig).digest('hex').slice(0, 10) : '' }
103
106
  }
104
107
 
105
- export function createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad, version = '', exported, log = () => {}, thumbDir = THUMB_DIR, downloads = path.join(os.homedir(), 'Downloads'), sessionCwd = async (id) => tracker.cwdOf(id), render = renderPack }) {
108
+ export function createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad, version = '', exported, log = () => {}, thumbDir = THUMB_DIR, downloads = path.join(os.homedir(), 'Downloads'), sessionCwd = async (id) => tracker.cwdOf(id), render = renderPack, github = createGitHub({ log }) }) {
106
109
  const lang = (body) => (body && body.lang === 'en' ? 'en' : 'zh')
110
+ // 这次运行里「分享到市场」打出来的包(一键投稿只投这些):zip 路径 → { ref, slug, title, license }
111
+ const shared = new Map()
107
112
 
108
113
  // 作品库里登记的、目录在哪(id → 记录):只认列得出来的,别让请求指到别的目录
109
114
  const byId = (id) => library.list().find((w) => idOf(w.dir) === id) || null
@@ -273,7 +278,8 @@ export function createLibraryRoutes({ admit, readBody, json, tracker, library, i
273
278
  const stem = slugOf(t.zh || t.en || path.basename(dir), 'design')
274
279
  let file = path.join(downloads, `${stem}.zip`)
275
280
  for (let i = 2; fs.existsSync(file) && i < 100; i++) file = path.join(downloads, `${stem}-${i}.zip`)
276
- fs.writeFileSync(file, zipOf(p), { flag: 'wx' })
281
+ const zip = zipOf(p)
282
+ fs.writeFileSync(file, zip, { flag: 'wx' })
277
283
  exported.add(file)
278
284
  if (!share) return json(res, 200, { ...out, path: file })
279
285
  // 作者这边记下:分享记号 + 这次填的名字介绍(下次分享预填、「我的作品」认得出已上架);从市场来的 from 留着
@@ -283,7 +289,10 @@ export function createLibraryRoutes({ admit, readBody, json, tracker, library, i
283
289
  const tmp = path.join(dir, `.design.json.${process.pid}.tmp`)
284
290
  fs.writeFileSync(tmp, JSON.stringify(mine, null, 2) + '\n')
285
291
  fs.renameSync(tmp, path.join(dir, 'design.json'))
286
- json(res, 200, { ...out, path: file, share: { ref: shareHash.slice(0, 12), slug: slugFor(t.en, t.zh, path.basename(dir)), title: t.zh || t.en || '' } })
292
+ const sh = { ref: shareHash.slice(0, 12), slug: slugFor(t.en, t.zh, path.basename(dir)), title: t.zh || t.en || '' }
293
+ // 一键投稿认这份:查过的内容指纹(重新打包也一样,投过的认得出)+ zip 本身的指纹(投之前被改过就不认)
294
+ shared.set(file, { ...sh, license, pack: packPrint(p.files), zipSha: crypto.createHash('sha256').update(zip).digest('hex') })
295
+ json(res, 200, { ...out, path: file, share: { ...sh, license } })
287
296
  } catch (e) {
288
297
  log(e)
289
298
  json(res, 500, { error: e.message })
@@ -356,5 +365,45 @@ export function createLibraryRoutes({ admit, readBody, json, tracker, library, i
356
365
  fs.createReadStream(file).on('error', () => res.end()).pipe(res)
357
366
  }
358
367
 
359
- return { works, workthumb, pack, usezip, inspire, inspimg }
368
+ // 一键投稿的错误:auth 要重新连 GitHub(不用 401,免得和 DSH 自己的登录混了)
369
+ const ghFail = (res, e) => {
370
+ if (!(e instanceof GhError)) { log(e); return json(res, 500, { error: 'device' }) }
371
+ json(res, e.code === 'auth' || e.code === 'who' ? 409 : e.code === 'busy' ? 429 : 502, { error: e.code, msg: String(e.message || '').slice(0, 200), status: e.status || 0 })
372
+ }
373
+
374
+ /** GET:连没连 GitHub、正在等输的码;POST { op: start | cancel | logout } */
375
+ async function ghauth(req, res) {
376
+ if (!admit(req, res)) return
377
+ if (req.method === 'GET') return json(res, 200, github.status())
378
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
379
+ let body
380
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
381
+ try {
382
+ if (body.op === 'start') return json(res, 200, await github.start())
383
+ if (body.op === 'cancel') github.cancel()
384
+ else if (body.op === 'logout') github.logout()
385
+ else return json(res, 400, { error: 'bad op' })
386
+ json(res, 200, github.status())
387
+ } catch (e) { ghFail(res, e) }
388
+ }
389
+
390
+ /** POST { path }:把刚才「分享到市场」打好的包直接投上去 → { url }(投稿 issue) */
391
+ async function submit(req, res) {
392
+ if (!admit(req, res)) return
393
+ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' })
394
+ let body
395
+ try { body = await readBody(req) } catch (e) { return json(res, 400, { error: e.message }) }
396
+ const file = String(body.path || '')
397
+ const s = shared.get(file)
398
+ let zip = null
399
+ try { zip = s ? fs.readFileSync(file) : null } catch { zip = null }
400
+ if (!s || !zip || crypto.createHash('sha256').update(zip).digest('hex') !== s.zipSha) return json(res, 404, { error: 'notShared' })
401
+ try {
402
+ const { zipSha, ...meta } = s
403
+ const r = await github.submit({ zip, ...meta, as: typeof body.login === 'string' ? body.login.slice(0, 39) : '' })
404
+ json(res, 200, { ok: true, ...r })
405
+ } catch (e) { ghFail(res, e) }
406
+ }
407
+
408
+ return { works, workthumb, pack, usezip, inspire, inspimg, ghauth, submit }
360
409
  }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * 一键投稿到设计市场(不用离开 DSH、不用拖 zip、不用装 git):
3
+ *
4
+ * 1. 连 GitHub:设备授权——插件给一个码,用户在 github.com/login/device 输进去点同意。
5
+ * 拿到的令牌只要 public_repo(动自己的公开仓库、开 issue),存在这台电脑上(只有自己能读),
6
+ * 不发给页面、不进日志;「断开」就删掉。
7
+ * 2. 投稿:zip 放进投稿人自己的仓库——内容仓库的主人直接放内容仓库的一个分支,
8
+ * 别人(包括有写权限的协作者)先 fork 一份放进去;只放一个提交,地址按提交号钉死(之后改不了内容)。
9
+ * 机器人只认「仓库主人 = 投稿人」的地址,所以协作者也得走自己的 fork。
10
+ * 3. 用投稿人的身份开投稿 issue,格式和网页表单一样(四个确认在插件里勾过了)。
11
+ * 之后和网页表单投稿完全一样:机器人下载、检查、转 PR、贴审核卡。
12
+ */
13
+
14
+ import crypto from 'node:crypto'
15
+ import fs from 'node:fs'
16
+ import path from 'node:path'
17
+ import { LIBRARY_DIR } from '../works.js'
18
+
19
+ // OAuth 应用「DSH Design Studio」(OrderG-X 名下,开了设备授权)的 Client ID:公开的,不是密钥
20
+ export const GH_CLIENT_ID = process.env.DSH_DESIGN_GH_CLIENT_ID ?? 'Ov23li7T6UcUOBKYE7Tc'
21
+ export const GALLERY = 'OrderG-X/dsh-design-gallery'
22
+ export const AUTH_FILE = path.join(LIBRARY_DIR, 'github.json')
23
+ const API = 'https://api.github.com'
24
+ const SCOPE = 'public_repo'
25
+ const UA = 'dsh-design-studio'
26
+ export const ZIP_MAX = 8 * 1024 * 1024 // 和机器人收稿的上限一样
27
+
28
+ // 投稿表单「授权」「确认」两栏的原文(机器人按表单的格式读)
29
+ export const FORM_LIC = { 'CC0-1.0': 'CC0-1.0(谁都能随便用,不用署名 / anyone can use it, no credit needed)', 'CC-BY-4.0': 'CC-BY-4.0(别人用要署你的名 / others must credit you)' }
30
+ const FORM_AGREE = [
31
+ '这是我自己(或用设计台)做的原创设计,图片都是自己做的或 CC0 / 公有领域 / This is my original design; all images are mine or CC0 / public domain',
32
+ '品牌是虚构的,没有仿冒真实网站、应用或机构 / The brand is made up and does not imitate a real site, app or organization',
33
+ '里面没有真实的个人信息 / It contains no real personal data',
34
+ '同意按上面选的授权公开,并收进设计市场 / I agree to publish it under the license above in the design gallery',
35
+ ]
36
+
37
+ /** 出错的种类(页面按 code 出提示):auth 要重新连、net 连不上 GitHub、denied 用户点了拒绝、expired 码过期… */
38
+ export class GhError extends Error {
39
+ constructor(code, msg = '', status = 0) {
40
+ super(msg || code)
41
+ this.code = code
42
+ this.status = status
43
+ }
44
+ }
45
+
46
+ /** 投稿 issue 的正文:和网页表单交出来的一样(「### 标题」一段一段),机器人照常读;开头记着包的指纹(重试时认出投过了) */
47
+ export function issueBody({ zipUrl, slug = '', license = 'CC0-1.0', pack = '' }) {
48
+ return [
49
+ '<!-- 设计台一键投稿 / Submitted from the design studio -->',
50
+ ...(/^[0-9a-f]{64}$/.test(pack) ? [`<!-- dsh-pack: ${pack} -->`] : []),
51
+ '### 设计包 / Design pack',
52
+ '',
53
+ zipUrl,
54
+ '',
55
+ '### 短名 / Short name',
56
+ '',
57
+ /^[a-z0-9-]{3,40}$/.test(slug) ? slug : '_No response_',
58
+ '',
59
+ '### 授权 / License',
60
+ '',
61
+ FORM_LIC[license] || FORM_LIC['CC0-1.0'],
62
+ '',
63
+ '### 确认 / Confirm',
64
+ '',
65
+ ...FORM_AGREE.map((x) => `- [X] ${x}`),
66
+ '',
67
+ ].join('\n')
68
+ }
69
+
70
+ /** 包的内容指纹:文件路径 + 内容(不含 zip 里的时间),同一套内容重新打包也一样 */
71
+ export function packPrint(files) {
72
+ const h = crypto.createHash('sha256')
73
+ for (const f of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
74
+ const d = Buffer.from(f.data)
75
+ h.update(`${f.path}\0${d.length}\0`)
76
+ h.update(d)
77
+ }
78
+ return h.digest('hex')
79
+ }
80
+
81
+ export function createGitHub({ file = AUTH_FILE, clientId = GH_CLIENT_ID, fetcher = (...a) => globalThis.fetch(...a), wait = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), log = () => {} } = {}) {
82
+ let flow = null // 正在等用户输码:{ code, uri, expiresAt, interval, error }
83
+ let busy = null // 正在投的(一次只投一个,连点不会开两个 issue)
84
+ let epoch = 0 // 每次「断开」加一:断开前发出去的换令牌、等输码,回来时作废,不能把授权又写回来
85
+ let gen = 0 // 每次开始连、取消、断开都加一:要码的请求回来时对不上就作废(不能在取消之后又冒出一个码)
86
+
87
+ function load() {
88
+ try {
89
+ const a = JSON.parse(fs.readFileSync(file, 'utf8'))
90
+ return a && typeof a.token === 'string' && a.token && typeof a.login === 'string' ? a : null
91
+ } catch { return null }
92
+ }
93
+ function save(a) {
94
+ fs.mkdirSync(path.dirname(file), { recursive: true })
95
+ const tmp = `${file}.${process.pid}.tmp`
96
+ fs.writeFileSync(tmp, JSON.stringify(a, null, 2) + '\n', { mode: 0o600 })
97
+ fs.renameSync(tmp, file)
98
+ try { fs.chmodSync(file, 0o600) } catch { /* Windows 不认,没关系 */ }
99
+ }
100
+ function clear() {
101
+ try { fs.rmSync(file, { force: true }) } catch { /* 删不掉下次再说 */ }
102
+ }
103
+
104
+ async function form(url, params) {
105
+ let r
106
+ try {
107
+ r = await fetcher(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': UA }, body: new URLSearchParams(params).toString(), signal: AbortSignal.timeout(20000) })
108
+ } catch (e) { throw new GhError('net', String((e && e.message) || e)) }
109
+ // GitHub 临时出毛病(限流、5xx):算连不上,授权留着,等会儿再试
110
+ if (r.status === 429 || r.status >= 500) throw new GhError('net', `HTTP ${r.status}`)
111
+ let j = null
112
+ try { j = await r.json() } catch { j = null }
113
+ if (!j || typeof j !== 'object') throw new GhError('net', `HTTP ${r.status}`)
114
+ return j
115
+ }
116
+
117
+ async function call(token, method, p, body) {
118
+ let r
119
+ try {
120
+ r = await fetcher(API + p, {
121
+ method,
122
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': UA, ...(body ? { 'Content-Type': 'application/json' } : {}) },
123
+ body: body ? JSON.stringify(body) : undefined,
124
+ signal: AbortSignal.timeout(90000),
125
+ })
126
+ } catch (e) { throw new GhError('net', String((e && e.message) || e)) }
127
+ let j = null
128
+ try { j = await r.json() } catch { j = null }
129
+ // 令牌被拒:只删这一个(请求途中用户可能已经断开又重新连上了,新令牌不能跟着删)
130
+ if (r.status === 401) {
131
+ const a = load()
132
+ if (a && a.token === token) clear()
133
+ throw new GhError('auth', 'token rejected', 401)
134
+ }
135
+ if (r.status < 200 || r.status >= 300) throw new GhError('api', String((j && j.message) || `HTTP ${r.status}`).slice(0, 200), r.status)
136
+ // 回包读不全(被截断、不是 JSON):当连不上,别把「没读到」当成「没有」接着往下走
137
+ if (!j || typeof j !== 'object') throw new GhError('net', `bad response ${r.status}`)
138
+ return j
139
+ }
140
+
141
+ const record = (j, who) => ({
142
+ token: j.access_token,
143
+ refresh: typeof j.refresh_token === 'string' ? j.refresh_token : '',
144
+ expiresAt: Number(j.expires_in) > 0 ? now() + Number(j.expires_in) * 1000 : 0,
145
+ refreshExpiresAt: Number(j.refresh_token_expires_in) > 0 ? now() + Number(j.refresh_token_expires_in) * 1000 : 0,
146
+ login: String(who.login),
147
+ id: Number(who.id) || 0,
148
+ })
149
+
150
+ /** 能用的令牌:快过期了先换新的;换不了就要重新连 */
151
+ async function token() {
152
+ const a = load()
153
+ if (!a) throw new GhError('auth')
154
+ if (!a.expiresAt || now() < a.expiresAt - 120000) return a.token
155
+ if (a.refresh && (!a.refreshExpiresAt || now() < a.refreshExpiresAt)) {
156
+ // 连不上 GitHub(form 抛 net):原样抛出去,授权留着,等会儿再试;GitHub 明说不行才要重新连
157
+ const at = epoch
158
+ const j = await form('https://github.com/login/oauth/access_token', { client_id: clientId, grant_type: 'refresh_token', refresh_token: a.refresh })
159
+ if (at !== epoch) throw new GhError('auth') // 等回包的时候用户断开了
160
+ if (typeof j.access_token === 'string' && j.access_token) {
161
+ save(record(j, a))
162
+ return j.access_token
163
+ }
164
+ // 没给令牌也没说为什么:当临时故障,授权留着
165
+ if (typeof j.error !== 'string' || !j.error) throw new GhError('net', 'refresh: no token')
166
+ }
167
+ clear()
168
+ throw new GhError('auth')
169
+ }
170
+
171
+ async function poll(f, deviceCode) {
172
+ const at = epoch
173
+ while (flow === f && at === epoch) {
174
+ await wait(f.interval * 1000)
175
+ if (flow !== f) return
176
+ if (now() > f.expiresAt) { f.error = 'expired'; return }
177
+ let j
178
+ try {
179
+ j = await form('https://github.com/login/oauth/access_token', { client_id: clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' })
180
+ } catch { continue } // 网络抖一下:接着等,码过期了自然停
181
+ if (flow !== f) return
182
+ if (j.error === 'authorization_pending') continue
183
+ if (j.error === 'slow_down') { f.interval = Math.max(f.interval + 5, Number(j.interval) || 0); continue }
184
+ if (j.error || typeof j.access_token !== 'string' || !j.access_token) { f.error = j.error === 'access_denied' ? 'denied' : j.error === 'expired_token' ? 'expired' : 'device'; return }
185
+ const who = await call(j.access_token, 'GET', '/user')
186
+ if (flow !== f || at !== epoch) return
187
+ save(record(j, who))
188
+ flow = null
189
+ return
190
+ }
191
+ }
192
+
193
+ /** 给页面看的状态:连上的账号、或者正在等输的码(令牌不出这个文件) */
194
+ function status() {
195
+ const a = load()
196
+ return { ready: !!clientId, login: a ? a.login : '', flow: flow ? { code: flow.code, uri: flow.uri, expiresAt: flow.expiresAt, error: flow.error } : null, busy: !!busy }
197
+ }
198
+
199
+ async function start() {
200
+ if (!clientId) throw new GhError('noApp')
201
+ flow = null
202
+ const my = ++gen
203
+ const j = await form('https://github.com/login/device/code', { client_id: clientId, scope: SCOPE })
204
+ if (my !== gen) return status() // 等码的时候点了取消、断开或者又点了一次连
205
+ if (typeof j.device_code !== 'string' || typeof j.user_code !== 'string') throw new GhError('device', String(j.error_description || j.error || ''))
206
+ const uri = /^https:\/\/github\.com\/login\/device\b/.test(String(j.verification_uri)) ? String(j.verification_uri) : 'https://github.com/login/device'
207
+ const f = { code: j.user_code.slice(0, 20), uri, expiresAt: now() + Math.min(Number(j.expires_in) || 900, 1800) * 1000, interval: Math.max(5, Number(j.interval) || 5), error: '' }
208
+ flow = f
209
+ poll(f, j.device_code).catch((e) => {
210
+ if (flow === f) f.error = e instanceof GhError ? e.code : 'device'
211
+ log(e)
212
+ })
213
+ return status()
214
+ }
215
+
216
+ function cancel() { gen++; flow = null }
217
+ function logout() {
218
+ epoch++
219
+ gen++
220
+ flow = null
221
+ clear()
222
+ }
223
+
224
+ async function submitOnce({ zip, title, ref, slug, license, pack: fp = '', as = '' }) {
225
+ if (!Buffer.isBuffer(zip) || !zip.length) throw new GhError('zip')
226
+ if (zip.length > ZIP_MAX) throw new GhError('big')
227
+ const tok = await token()
228
+ const me = await call(tok, 'GET', '/user')
229
+ const login = String(me.login || '')
230
+ if (!/^[A-Za-z0-9-]{1,39}$/.test(login)) throw new GhError('api', 'no login')
231
+ // 面板上显示的是另一个账号(别的窗口断开又连了别人):先不投,让用户看清楚用谁投再点
232
+ if (as && String(as).toLowerCase() !== login.toLowerCase()) throw new GhError('who', login)
233
+ // 同一个包投过、那条投稿还开着(上次 issue 建好了但回包丢了、用户又点了一次):直接给那条,不再开第二个。
234
+ // 指纹按包里的文件内容算(routes 打包时算好传进来),重新打包时间变了也认得出;没传就按 zip 本身
235
+ const pack = /^[0-9a-f]{64}$/.test(fp) ? fp : crypto.createHash('sha256').update(zip).digest('hex')
236
+ const mark = `<!-- dsh-pack: ${pack} -->`
237
+ let had = null
238
+ for (let page = 1; !had; page++) {
239
+ // 开着的超过一千条还没翻完:查不全就不投(宁可不投,也不重复开)
240
+ if (page > 10) throw new GhError('api', 'too many open issues to check for duplicates')
241
+ const mine = await call(tok, 'GET', `/repos/${GALLERY}/issues?creator=${encodeURIComponent(login)}&state=open&per_page=100&page=${page}`)
242
+ if (!Array.isArray(mine)) throw new GhError('net', 'issues: not a list')
243
+ had = mine.find((x) => x && !x.pull_request && typeof x.body === 'string' && x.body.includes(mark) && /^https:\/\/github\.com\//.test(String(x.html_url))) || null
244
+ if (mine.length < 100) break
245
+ }
246
+ if (had) return { url: had.html_url, number: had.number, login, fork: '', again: true }
247
+ // 放 zip 的仓库:内容仓库的主人放内容仓库,别人(协作者也一样)放自己的 fork——机器人只认「仓库主人 = 投稿人」
248
+ let target = GALLERY
249
+ if (login.toLowerCase() !== GALLERY.split('/')[0].toLowerCase()) {
250
+ const fk = await call(tok, 'POST', `/repos/${GALLERY}/forks`, { default_branch_only: true })
251
+ const owner = String((fk.owner && fk.owner.login) || '')
252
+ if (typeof fk.full_name !== 'string' || owner.toLowerCase() !== login.toLowerCase() || !/^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/.test(fk.full_name)) throw new GhError('fork', String(fk.full_name || ''))
253
+ target = fk.full_name
254
+ }
255
+ // fork 是后台慢慢建的:建好之前写不进去,隔几秒再试(最多一分多钟)
256
+ let blob
257
+ for (let i = 0; ; i++) {
258
+ try {
259
+ blob = await call(tok, 'POST', `/repos/${target}/git/blobs`, { content: zip.toString('base64'), encoding: 'base64' })
260
+ break
261
+ } catch (e) {
262
+ if (i >= 14 || !(e instanceof GhError) || !(e.status === 404 || e.status === 409)) throw e
263
+ await wait(5000)
264
+ }
265
+ }
266
+ const tree = await call(tok, 'POST', `/repos/${target}/git/trees`, { tree: [{ path: 'submission.zip', mode: '100644', type: 'blob', sha: blob.sha }] })
267
+ const commit = await call(tok, 'POST', `/repos/${target}/git/commits`, { message: `design submission ${ref}`, tree: tree.sha, parents: [] })
268
+ if (!/^[0-9a-f]{40}$/.test(String(commit.sha))) throw new GhError('api', 'no commit')
269
+ // 挂一个分支,免得提交被当成没人要的清理掉
270
+ await call(tok, 'POST', `/repos/${target}/git/refs`, { ref: `refs/heads/dsh-submit/${ref}-${now().toString(36)}`, sha: commit.sha })
271
+ const zipUrl = `https://github.com/${target}/raw/${commit.sha}/submission.zip`
272
+ const issue = await call(tok, 'POST', `/repos/${GALLERY}/issues`, {
273
+ title: `投稿 / Submission: ${String(title).replace(/\s+/g, ' ').trim().slice(0, 60)} · ${ref}`,
274
+ body: issueBody({ zipUrl, slug, license, pack }),
275
+ labels: ['submission'], // 外人开的会被 GitHub 悄悄去掉;机器人按标题认,回复时补上
276
+ })
277
+ if (!/^https:\/\/github\.com\//.test(String(issue.html_url))) throw new GhError('api', 'no issue')
278
+ return { url: issue.html_url, number: issue.number, login, fork: target !== GALLERY ? target : '' }
279
+ }
280
+
281
+ async function submit(opts) {
282
+ if (busy) throw new GhError('busy')
283
+ busy = submitOnce(opts)
284
+ try { return await busy } finally { busy = null }
285
+ }
286
+
287
+ return { status, start, cancel, logout, submit, token }
288
+ }
package/lib/handoff.js CHANGED
@@ -17,6 +17,7 @@ import { pathToFileURL } from 'node:url'
17
17
  import { prepare } from './look.js'
18
18
  import { allScreens } from './core.js'
19
19
  import { readTweaks, shownValue } from './tweaks.js'
20
+ import { annotationsMd } from './annotations.js'
20
21
  import { tokensOf } from './system.js'
21
22
 
22
23
  export const HANDOFF_DIR = 'handoff'
@@ -333,7 +334,7 @@ export function unlinkIfLink(file) {
333
334
  * 生成交接包。screens:[{ key, url, label }](预览服务器上的地址);root:设计目录。
334
335
  * @returns { file, dir, md, shots, rows }
335
336
  */
336
- export async function buildHandoff(browser, { root, screens, kind = 'web', size = [1280, 800], framework = 'react', dest = '', project = null, system = '', now = new Date() }) {
337
+ export async function buildHandoff(browser, { root, screens, kind = 'web', size = [1280, 800], framework = 'react', dest = '', project = null, system = '', annotations = null, now = new Date() }) {
337
338
  const dir = path.join(root, HANDOFF_DIR)
338
339
  const shotDir = path.join(dir, 'shots')
339
340
  // handoff/、handoff/shots/ 得是设计目录里真的文件夹:是软链接就可能删到、写到别处去
@@ -347,7 +348,7 @@ export async function buildHandoff(browser, { root, screens, kind = 'web', size
347
348
  const rows = browser && browser.available() ? await shootScreens(browser, list, size, kind, shotDir) : list.map((sc) => ({ key: sc.key, label: sc.label, title: '', links: [], shots: [], error: '没有 Chrome / Edge,没截图' }))
348
349
  const htmlByKey = new Map()
349
350
  for (const sc of list) { try { htmlByKey.set(sc.key, fs.readFileSync(path.join(root, sc.key), 'utf8')) } catch { /* 读不了 */ } }
350
- const md = handoffMd({ root, rows, kind, size, framework, dest, project, system, htmlByKey, more: Math.max(0, screens.length - MAX_SCREENS), now })
351
+ const md = handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations, htmlByKey, more: Math.max(0, screens.length - MAX_SCREENS), now })
351
352
  const file = path.join(dir, 'HANDOFF.md')
352
353
  unlinkIfLink(file)
353
354
  fs.writeFileSync(file, md)
@@ -355,7 +356,7 @@ export async function buildHandoff(browser, { root, screens, kind = 'web', size
355
356
  }
356
357
 
357
358
  /** 交接说明 */
358
- export function handoffMd({ root, rows, kind, size, framework, dest, project, system, htmlByKey, more = 0, now = new Date() }) {
359
+ export function handoffMd({ root, rows, kind, size, framework, dest, project, system, annotations = null, htmlByKey, more = 0, now = new Date() }) {
359
360
  const fw = FRAMEWORKS[framework] || null
360
361
  const same = framework === 'same' && project && project.framework
361
362
  const fwLabel = same ? `${project.label}(跟项目一样)` : fw ? fw.label : framework
@@ -518,6 +519,9 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
518
519
  if (tw && tw.list.length) lines.push(`- 调节滑块(tweaks.json):${tw.list.map((k) => `${k.label}(${k.var || k.attr},现在是 ${shownValue(k, k.value)})`).join('、')}。最终值已经写在样式里;要在产品里留着可调,就做成主题设置(改同一个 CSS 变量 / <html> 属性)。`)
519
520
  lines.push('')
520
521
 
522
+ // 业务规则(业务标注开着才有)
523
+ lines.push(...annotationsMd(annotations, new Set(htmlByKey.keys()), annotations ? new Set(allScreens(root)) : null))
524
+
521
525
  // 素材
522
526
  const assets = []
523
527
  const walk = (d, rel, depth) => {
package/lib/index.js CHANGED
@@ -50,10 +50,11 @@ import { createHub, webOrigins, trustedOrigins, resolveInRoot, ERR_CATCHER, defa
50
50
  import { bundle, inlinePicker, strictMeta, MAX_TOTAL as BUNDLE_MAX } from './bundle.js'
51
51
  import { createLibrary } from './works.js'
52
52
  import { createInspiration } from './inspire.js'
53
+ import { pickStyleText } from './styles.js'
53
54
  import { createLibraryRoutes } from './gallery/routes.js'
54
55
  import { createMarket } from './gallery/market.js'
55
56
  import { createMarketRoutes } from './gallery/market-routes.js'
56
- import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
57
+ import { createPhotos, loadPhotoIndex, searchPhotos, onlyByTheme, ratioNote, isPhotoAsset, orientOf, MAX_PHOTOS } from './photos.js'
57
58
  import { createTracker, parseTarget, findRule, KINDS } from './core.js'
58
59
  import { createDrafts } from './draft.js'
59
60
  import { createHistory } from './history.js'
@@ -64,6 +65,7 @@ import { createBrowser } from './browser.js'
64
65
  import { designOf, fitSize, metaOfFile, sizeOf, pickScreens, measureAll, shootAll, cropIssues, formatMeasure, issueSnapshot, formatShots, whereOf, MAX_SCREENS, MAX_SIZES, MAX_SHOTS, MAX_CROPS } from './look.js'
65
66
  import { SYSTEMS_DIR, extractSystem, listSystems, setDefault, skillSection } from './system.js'
66
67
  import { readTweaks, applyTweaks, lintTweaks } from './tweaks.js'
68
+ import { readAnnotations, lintAnnotations, annotationFindings, annotationSection } from './annotations.js'
67
69
  import { FRAMEWORKS, detectProject, projectFor, defaultFramework, buildHandoff, compareScreens, implUrl, defaultDest, pickedDest, within, pinRoots } from './handoff.js'
68
70
 
69
71
  export const name = 'dsh-design-studio'
@@ -90,7 +92,7 @@ const SKILL_RANK = 600 // 和 DSH 自带的技能同一档;用户 / 项目里
90
92
  * 几行之间靠这个互通(同一个包里的模块 Node 只加载一次):工作台起来后放 tracker、无头浏览器(browser);
91
93
  * 「自动打开预览」那行开着时 autoOpen > 0
92
94
  */
93
- export const studio = { tracker: null, autoOpen: 0, offline: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
95
+ export const studio = { tracker: null, autoOpen: 0, offline: 0, annotations: 0, check: null, browser: null, market: null, photos: null, sessionCwd: null, log: () => {} }
94
96
 
95
97
  /** 设计技能:模型做界面设计时加载(DSH 的 skill 工具),也能让用户手动调 */
96
98
  export const designSkill = {
@@ -116,6 +118,7 @@ export const skillProvider = {
116
118
  // 用户的设计系统(默认用哪套、库里有哪些)每次现读,提了新的下次加载技能就知道
117
119
  let extra = ''
118
120
  try { extra = skillSection() } catch (e) { studio.log(e) }
121
+ if (studio.annotations > 0) extra += annotationSection()
119
122
  return { name, description, whenToUse, invocation, provider, source, resourceBase, content: (await fs.promises.readFile(designSkill.locator, 'utf8')) + extra }
120
123
  },
121
124
  }
@@ -245,12 +248,13 @@ export const checkTool = {
245
248
  const { snap, kind } = design
246
249
  const want = sizesFrom(a.sizes, kind)
247
250
  const b = studio.browser
251
+ const anAt = annotationsAt(id) // 开始量时的设计目录和标注:量的过程中换了设计也不串
248
252
  if (b && b.available()) {
249
253
  try {
250
254
  const pick = pickScreens(snap, a.screens, MAX_SCREENS)
251
255
  if (!pick.list.length) return { text: `没找到要量的屏:${pick.missing.join('、')}。现在有:${(snap.screens || []).map((x) => x.key).join('、') || snap.focus}` }
252
256
  const sizes = want.sizes.length ? want.sizes : [await fitted(b, design, a.screens)]
253
- const rows = await measureAll(b, { screens: pick.list, sizes, kind, dark: !!a.dark, locate: (items) => locateRules(studio.tracker.stateOf(id), items) })
257
+ const rows = await measureAll(b, { screens: pick.list, sizes, kind, dark: !!a.dark, annots: annotsByPage(anAt.ann), locate: (items) => locateRules(studio.tracker.stateOf(id), items) })
254
258
  if (rows.some((r) => !r.error)) {
255
259
  // 同一个会话上次量的结果:这次比一比修好了几个、新出了几个
256
260
  const prev = lastChecks.get(id) || null
@@ -269,7 +273,7 @@ export const checkTool = {
269
273
  while (lastChecks.size > 20) lastChecks.delete(lastChecks.keys().next().value)
270
274
  if (want.bad.length) text += `\n认不出的尺寸(没量):${want.bad.join('、')},写成 375x667 或 375`
271
275
  if (want.more) text += `\n尺寸太多,只量了前 ${MAX_SIZES} 种`
272
- text += tweakNotes(id)
276
+ text += tweakNotes(id) + annotationNotes(anAt, rows)
273
277
  return kept && kept.images ? { text, images: kept.images } : { text }
274
278
  }
275
279
  studio.log(new Error(`check_design 无头浏览器没量成:${rows[0] && rows[0].error}`))
@@ -283,10 +287,41 @@ export const checkTool = {
283
287
  const note = want.sizes.length || a.dark ? '(这台电脑上没找到能用的 Chrome / Edge,没法按指定尺寸 / 深色量;下面是右侧栏按它现在显示的尺寸量的)\n' : ''
284
288
  if (!r) return { text: '右侧栏「设计工作台」现在没开着,量不了。照 ui-design 技能里的「自查」清单自己过一遍。' }
285
289
  if (!r.error && !r.measured) return { text: '右侧栏开着,但预览页面没回应,这次没量成(可能还在加载)。过一会儿再调一次,或照 ui-design 技能里的「自查」清单自己过一遍。' }
286
- return { text: note + (r.error || r.text) + tweakNotes(id) }
290
+ return { text: note + (r.error || r.text) + tweakNotes(id) + annotationNotes(anAt, null) }
287
291
  },
288
292
  }
289
293
 
294
+ /** 这个会话现在的设计目录和里面的业务标注(开关关着、不是本地文件时 root 是 '') */
295
+ function annotationsAt(id) {
296
+ if (!(studio.annotations > 0)) return { root: '', ann: null }
297
+ try {
298
+ const t = studio.tracker.stateOf(id).target
299
+ if (t && t.kind === 'file') return { root: t.root, ann: readAnnotations(t.root) }
300
+ } catch (e) { studio.log(e) }
301
+ return { root: '', ann: null }
302
+ }
303
+
304
+ /** 按屏分好的业务标注:无头浏览器量的时候顺手核对定位 */
305
+ function annotsByPage(r) {
306
+ if (!r || !r.list.length) return null
307
+ const m = new Map()
308
+ for (const a of r.list) { if (!m.has(a.page)) m.set(a.page, []); m.get(a.page).push({ id: a.id, selector: a.selector, fallbackText: a.fallbackText }) }
309
+ return m
310
+ }
311
+
312
+ /** 业务标注写坏的、定位不到的:check_design 末尾附上(at:开始量时的目录和标注;rows:无头浏览器量的结果,没量成是 null) */
313
+ function annotationNotes(at, rows) {
314
+ if (!at.root) return ''
315
+ let list = []
316
+ try {
317
+ list = lintAnnotations(at.root)
318
+ const r = at.ann
319
+ if (r && rows) list.push(...annotationFindings(r.list, rows.filter((x) => Array.isArray(x.annots)).map((x) => ({ page: x.key, list: x.annots }))))
320
+ else if (r && r.list.length) list.push('这次没有无头浏览器,选择器定位不到的情况没核对;右侧栏「业务标注」面板里能看到')
321
+ } catch (e) { studio.log(e) }
322
+ return list.length ? `\n\n业务标注(annotations.json):\n${list.map((x) => `- ${x}`).join('\n')}` : ''
323
+ }
324
+
290
325
  /** 调节滑块(tweaks.json)有没有真接上:check_design 末尾附上 */
291
326
  function tweakNotes(id) {
292
327
  let list = []
@@ -490,7 +525,7 @@ export const handoffTool = {
490
525
  if (framework === 'same' && !project.framework) return { text: `${dest} 里没有认得出的前端项目(package.json 里没有 React / Vue / Next / uni-app …,也不是 HBuilderX 或微信原生小程序的项目):framework 选 react、vue、next、html、uniapp 或 weapp。` }
491
526
  let r
492
527
  try {
493
- r = await buildHandoff(studio.browser, { root: t.root, screens: pick.list, kind, size, framework, dest, project, system: systemOfDir(t.root) })
528
+ 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 })
494
529
  } catch (e) {
495
530
  return { text: `没写成交接包:${String((e && e.message) || e).slice(0, 200)}` }
496
531
  }
@@ -552,7 +587,7 @@ export const photoTool = {
552
587
  const list = placed.map(({ p, rel }, i) => `${i + 1}. ${rel}(${ORIENT[orientOf(p.w, p.h)]} ${p.w}×${p.h})alt:${p.alt} / ${p.altEn}`)
553
588
  return {
554
589
  text:
555
- `${broad ? `按题材找到 ${placed.length} 张(没有和「${query}」里具体画面对得上的标签,看描述合不合适再用;不合适就用 CSS / SVG 画,并告诉用户这里需要什么样的照片)` : `找到 ${placed.length} 张`},已放进 ${path.join(dir, 'assets')}:\n${list.join('\n')}\n${few}` +
590
+ `${broad ? `按题材找到 ${placed.length} 张(没有和「${query}」里具体画面对得上的标签,看描述合不合适再用;不合适就用 CSS / SVG 画,并告诉用户这里需要什么样的照片)` : `找到 ${placed.length} 张`},已放进 ${path.join(dir, 'assets')}:\n${list.join('\n')}\n${few}${ratioNote(placed.map((x) => x.p), ratio)}` +
556
591
  '这是按关键词找的,先看上面的描述和需求对不对得上,对不上的别用(没用上的图不会进分享包)。\n' +
557
592
  '用法:<img src="assets/文件名" alt="…"> 配 object-fit: cover;alt 按界面语言选一个;HTML 不在这个文件夹时改相对路径。\n' +
558
593
  '这些是 AI 生成的示意图,不是用户真实的店铺或产品:别写「实拍」,也别把图上的场景当事实写进文案;做完告诉用户上线前换成真实照片。',
@@ -567,6 +602,29 @@ export const photoTool = {
567
602
  },
568
603
  }
569
604
 
605
+ /** pick_style 工具:用户没定风格时按题材挑一张风格卡(模型自己定,消费类题目总落回米色暖调;给了具体配色它照做得很好) */
606
+ export const styleTool = {
607
+ name: 'pick_style',
608
+ description:
609
+ '新做一套设计、用户没定风格时,开工前先调这个:按题材挑一张风格卡,返回整套配色、字体、圆角阴影和要点,照它定进 tokens.css。' +
610
+ '用户点了风格卡(消息里有〔风格〕)、自己定了具体的风格或配色、或有默认的品牌设计系统时不用调;只说「你定」「帮我推荐一个」「出几个风格挑」算没定,要调。',
611
+ parameters: specToJsonSchema({
612
+ subject: { type: 'string', required: true, description: '这次要做什么,直接写用户的原话' },
613
+ kind: { type: 'string', enum: ['web', 'app', 'miniprogram', 'tablet', 'desktop', 'poster', 'slides', 'email'], description: '设计类型' },
614
+ count: { type: 'number', description: '要几个方向,1–3,默认 1;要先出三个方向时填 3,每个方向一张不同的卡' },
615
+ }),
616
+ output: {
617
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string' } }, required: ['text'] },
618
+ render: (_args, value) => [{ type: 'text', text: value.text }],
619
+ },
620
+ async execute(args) {
621
+ const a = args || {}
622
+ const subject = typeof a.subject === 'string' ? a.subject.trim() : ''
623
+ if (!subject) return { text: 'subject 不能空:写这次要做什么,用用户的原话。' }
624
+ return { text: pickStyleText(subject, typeof a.kind === 'string' ? a.kind : '', a.count) }
625
+ },
626
+ }
627
+
570
628
  /** compare_design 工具:设计稿的一屏和做出来的页面按同样尺寸截图,逐像素比 */
571
629
  export const compareTool = {
572
630
  name: 'compare_design',
@@ -736,6 +794,7 @@ export function apply(ctx) {
736
794
  log,
737
795
  history,
738
796
  drafts,
797
+ skipAnnots: () => studio.annotations > 0, // 业务标注开着时这个文件只给右侧栏看,改了不刷新页面
739
798
  strict: { html: (buf) => library.strictHtml(buf) || market.strictHtml(buf), root: (dir) => library.strictRoot(dir) || market.isStaging(dir), versions: (dir) => library.strictVersions(dir) },
740
799
  // 桌面版的 dsh-app://app 是默认就认的;这里补上 DSH 网页端的地址,和 DSH 配置里声明的对外地址(反向代理 / 域名)
741
800
  parents: () => {
@@ -844,6 +903,18 @@ export function apply(ctx) {
844
903
  }
845
904
  }, 'dsh-design-studio: check')
846
905
 
906
+ /** 业务标注:开关开着才有这个键(null = 还没有文件)。an 是右侧栏手上那份的签名,没变就不再传一遍(一份可能上百 KB,轮询很勤) */
907
+ function annotsField(session, an = '') {
908
+ const t = tracker.stateOf(session).target
909
+ if (!(studio.annotations > 0) || !t || t.kind !== 'file') return {}
910
+ let annotations = null
911
+ try {
912
+ const r = readAnnotations(t.root)
913
+ annotations = r && an && r.sig === an ? { sig: r.sig, same: true } : r
914
+ } catch (e) { log(e) }
915
+ return { annotations }
916
+ }
917
+
847
918
  function state(req, res) {
848
919
  if (!admit(req, res)) return
849
920
  const session = new URL(req.url, 'http://x').searchParams.get('session') || ''
@@ -854,7 +925,7 @@ export function apply(ctx) {
854
925
  let tweaks = null
855
926
  if (t && t.kind === 'file') { try { tweaks = readTweaks(t.root) } catch (e) { log(e) } }
856
927
  const snap = tracker.snapshot(session)
857
- json(res, 200, { ...snap, strict: strictScreens(snap), phone: { on: ph.on, seen: ph.seen || 0 }, tweaks, ...(c ? { checkReq: c.id } : {}) })
928
+ json(res, 200, { ...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 } : {}) })
858
929
  }
859
930
 
860
931
  /** 正在看的几屏里,哪些是别人做的、没改过的(地址列表):右侧栏给它们的 iframe 加沙盒、不给剪贴板 */
@@ -988,7 +1059,7 @@ export function apply(ctx) {
988
1059
  // 输入框里写的相对路径按会话目录算(新会话也问 DSH 要)
989
1060
  const target = parseTarget(body.target, await sessionCwd(session))
990
1061
  await tracker.setTarget(session, target, { source: 'user', popup: false })
991
- json(res, 200, tracker.snapshot(session))
1062
+ json(res, 200, { ...tracker.snapshot(session), ...annotsField(session) })
992
1063
  } catch (e) {
993
1064
  json(res, 400, { error: e.message })
994
1065
  }
@@ -1005,7 +1076,7 @@ export function apply(ctx) {
1005
1076
  for (const k of ['kind', 'size', 'view', 'focus']) if (typeof body[k] === 'string') patch[k] = body[k]
1006
1077
  try {
1007
1078
  await tracker.setView(session, patch)
1008
- json(res, 200, tracker.snapshot(session))
1079
+ json(res, 200, { ...tracker.snapshot(session), ...annotsField(session) })
1009
1080
  } catch (e) {
1010
1081
  json(res, 400, { error: e.message })
1011
1082
  }
@@ -1302,7 +1373,7 @@ export function apply(ctx) {
1302
1373
  const lib = createLibraryRoutes({ admit, readBody, json, tracker, library, inspiration, studio, open, storeLoad: fileStore.load, version: VERSION, exported, log, sessionCwd })
1303
1374
  const mk = createMarketRoutes({ admit, readBody, json, tracker, library, market, open, systemsDir: SYSTEMS_DIR, log, sessionCwd })
1304
1375
 
1305
- const routes = { works: lib.works, workthumb: lib.workthumb, pack: lib.pack, usezip: lib.usezip, 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, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, systhumb: systhumbRoute, project: projectRoute }
1376
+ const routes = { works: lib.works, workthumb: lib.workthumb, 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, reveal: revealRoute, phone: phoneRoute, check: checkRoute, locate: locateRoute, tweak: tweakRoute, systems: systemsRoute, systhumb: systhumbRoute, project: projectRoute }
1306
1377
  for (const [key, handler] of Object.entries(routes)) {
1307
1378
  ctx.effect(() => ctx.webServer.register({
1308
1379
  kind: 'exact',