dsh-design-studio 1.2.0 → 1.3.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/README.en.md +1 -0
- package/README.md +1 -0
- package/lib/bundle.js +19 -15
- package/lib/client.js +254 -10
- package/lib/fonts-index.json +320 -0
- package/lib/fonts-preview.json +1 -0
- package/lib/fonts.js +352 -0
- package/lib/gallery/pack.js +7 -0
- package/lib/handoff.js +7 -0
- package/lib/history.js +2 -0
- package/lib/htmlpack.js +30 -5
- package/lib/index.js +191 -9
- package/lib/picker.js +47 -4
- package/lib/serve.js +36 -2
- package/lib/tool.js +3 -2
- package/lib/tweaks.js +135 -4
- package/package.json +1 -1
- package/skills/ui-design/SKILL.md +3 -1
package/lib/fonts.js
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 字体库(issue #31):免费可商用(SIL OFL 1.1)的网页字体。面板里点选、模型调 use_fonts,字体文件复制进设计目录的 dsh-fonts/
|
|
3
|
+
* (设计台专用的文件夹:不和设计自己放字体的 fonts/ 撞名),变量所在的样式里加一段设计台管的 @font-face。
|
|
4
|
+
*
|
|
5
|
+
* - 目录 fonts-index.json 随插件发(名字、分类、sha256),预览 fonts-preview.json 是名字画成的 SVG 路径(图形,不是字体)。
|
|
6
|
+
* - 字体在 npm 包 dsh-design-fonts 里,第一次用到才下载;每个文件按目录里钉死的 sha256 核对。「设计库不联网」开着就不下载。
|
|
7
|
+
* - @font-face 那段只认明确选过的(面板「存下」、use_fonts):开头标记里记着 id。旧设计的字体栈里本来就写着 "Noto Serif SC"
|
|
8
|
+
* 这类当系统字体的后备,不能因为名字对上就去下载、复制、改样子。
|
|
9
|
+
* - 那段里的只在「这次操作把它换走了、整套设计里一处都不再写它的名字」时去掉(drop);别的时候只加不减。
|
|
10
|
+
*/
|
|
11
|
+
import crypto from 'node:crypto'
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import os from 'node:os'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
|
|
17
|
+
export const FONTS_CACHE = process.env.DSH_DESIGN_FONTS_CACHE || path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'fonts')
|
|
18
|
+
export const FONT_DIR = 'dsh-fonts'
|
|
19
|
+
export const MAX_FONTS = 4 // use_fonts 一次最多几款
|
|
20
|
+
const INDEX_FILE = fileURLToPath(new URL('./fonts-index.json', import.meta.url))
|
|
21
|
+
const PREVIEW_FILE = fileURLToPath(new URL('./fonts-preview.json', import.meta.url))
|
|
22
|
+
const ID_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/
|
|
23
|
+
const CAP = 30 * 1024 * 1024
|
|
24
|
+
const LIMITS = { files: 100, file: 6 * 1024 * 1024, total: 40 * 1024 * 1024 }
|
|
25
|
+
const RETRY_MS = 60e3
|
|
26
|
+
const TIMING = { stagger: 8000, each: 60000, total: 120000 }
|
|
27
|
+
const CATS = new Set(['sans', 'serif', 'display', 'hand', 'mono'])
|
|
28
|
+
|
|
29
|
+
const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex')
|
|
30
|
+
// 版本号比大小(和 gallery/market.js 的 vcmp 一样;这里不引它,版本记录也要用这个文件,免得绕成环)
|
|
31
|
+
const vcmp = (a, b) => {
|
|
32
|
+
const pa = String(a || '0').split(/[.+-]/).slice(0, 3).map((n) => parseInt(n, 10) || 0)
|
|
33
|
+
const pb = String(b || '0').split(/[.+-]/).slice(0, 3).map((n) => parseInt(n, 10) || 0)
|
|
34
|
+
for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0) ? 1 : -1
|
|
35
|
+
return 0
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 每类后面跟的系统字体:字体库只裁了常用字,不在里面的字、没下载到时由它们顶上(Mac / Windows 成对写) */
|
|
39
|
+
export const FALLBACK = {
|
|
40
|
+
sans: '"PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
|
|
41
|
+
serif: '"Songti SC", "SimSun", serif',
|
|
42
|
+
display: '"PingFang SC", "Microsoft YaHei", system-ui, sans-serif',
|
|
43
|
+
hand: '"Kaiti SC", "KaiTi", serif',
|
|
44
|
+
mono: 'Menlo, Consolas, "PingFang SC", "Microsoft YaHei", monospace',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 读目录;格式不对的条目不要 */
|
|
48
|
+
export function loadFontIndex(file = INDEX_FILE) {
|
|
49
|
+
let raw
|
|
50
|
+
try { raw = JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
51
|
+
if (!raw || raw.format !== 1 || typeof raw.package !== 'string' || typeof raw.version !== 'string' || !Array.isArray(raw.fonts)) return null
|
|
52
|
+
const fonts = raw.fonts.filter((f) => f && ID_RE.test(String(f.id)) && /^[0-9a-f]{64}$/.test(String(f.sha256)) && f.size > 0 && CATS.has(f.cat) &&
|
|
53
|
+
typeof f.family === 'string' && /^[A-Za-z0-9 ]{1,40}$/.test(f.family) && f.file === `fonts/${f.id}.woff2`)
|
|
54
|
+
return { ...raw, fonts }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 预览:{ id: { w, h, d } }(d 是 SVG 路径,字体单位、y 向下) */
|
|
58
|
+
export function loadFontPreviews(file = PREVIEW_FILE) {
|
|
59
|
+
try {
|
|
60
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
61
|
+
return raw && typeof raw === 'object' ? raw : {}
|
|
62
|
+
} catch { return {} }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const stackOf = (f) => `"${f.family}", ${FALLBACK[f.cat] || FALLBACK.sans}`
|
|
66
|
+
|
|
67
|
+
const norm = (s) => String(s || '').normalize('NFKC').toLowerCase().replace(/["'\s_-]+/g, '')
|
|
68
|
+
|
|
69
|
+
/** 字体栈里的第一个名字(去引号) */
|
|
70
|
+
export function firstFamily(stack) {
|
|
71
|
+
const m = /^\s*(?:"([^"]*)"|'([^']*)'|([^,]*))/.exec(String(stack || ''))
|
|
72
|
+
return m ? (m[1] ?? m[2] ?? m[3] ?? '').trim() : ''
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 字体栈打头的是不是字体库里的(是就给那款) */
|
|
76
|
+
export function libFontOf(index, stack) {
|
|
77
|
+
if (!index) return null
|
|
78
|
+
const fam = firstFamily(stack).toLowerCase()
|
|
79
|
+
return (fam && index.fonts.find((f) => f.family.toLowerCase() === fam)) || null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 按名字找:id、CSS 名、中文名、英文名都认(大小写、空格、引号不计) */
|
|
83
|
+
export function findFont(index, name) {
|
|
84
|
+
const n = norm(name)
|
|
85
|
+
if (!index || !n) return null
|
|
86
|
+
return index.fonts.find((f) => [f.id, f.family, f.zh, f.en].some((x) => norm(x) === n)) || null
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ── 设计台管的 @font-face 那段 ──────────────────────────────────────────────
|
|
90
|
+
// /* dsh-fonts: noto-serif-sc inter | 设计台字体库 …(这段由设计台管,别手改)*/ … /* /dsh-fonts */
|
|
91
|
+
|
|
92
|
+
const BLOCK_RE = /\/\*\s*dsh-fonts:([^*]*?)\|[^*]*\*\/[\s\S]*?\/\*\s*\/dsh-fonts\s*\*\/[ \t]*(?:\r?\n)?/g
|
|
93
|
+
const BLOCK_HEAD_RE = /\/\*\s*dsh-fonts:([^*|]*)\|/
|
|
94
|
+
|
|
95
|
+
/** 文件里那段记着的 id(没有那段给 []) */
|
|
96
|
+
export function fontBlockIds(text) {
|
|
97
|
+
const m = BLOCK_HEAD_RE.exec(String(text || ''))
|
|
98
|
+
return m ? [...new Set(m[1].trim().split(/\s+/).filter((x) => ID_RE.test(x)))] : []
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 去掉那段(分享包、版本比较用) */
|
|
102
|
+
export const stripFontBlock = (text) => String(text).replace(BLOCK_RE, '')
|
|
103
|
+
|
|
104
|
+
/** 那段的文字:prefix 是这个文件到 fonts/ 的相对路径(「fonts」「../fonts」),nl 用文件自己的换行 */
|
|
105
|
+
export function fontBlock(fonts, prefix = FONT_DIR, nl = '\n') {
|
|
106
|
+
if (!fonts.length) return ''
|
|
107
|
+
const lines = [`/* dsh-fonts: ${fonts.map((f) => f.id).join(' ')} | 设计台字体库(SIL OFL 1.1,免费可商用),文件在 ${FONT_DIR}/。这段由设计台管,别手改 */`]
|
|
108
|
+
for (const f of fonts) {
|
|
109
|
+
// 只有一个字重的也写成 100 900:标题要 700、800 时浏览器就不会自己把它描粗(毛笔字、站酷那几款描粗了很难看)
|
|
110
|
+
const w = Array.isArray(f.weights) && f.weights.length === 2 ? `${f.weights[0]} ${f.weights[1]}` : '100 900'
|
|
111
|
+
lines.push(`@font-face { font-family: "${f.family}"; src: url("${prefix}/${f.id}.woff2") format("woff2"); font-weight: ${w}; font-display: swap; }`)
|
|
112
|
+
}
|
|
113
|
+
lines.push('/* /dsh-fonts */')
|
|
114
|
+
return lines.join(nl) + nl
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* CSS 文字里放那段的位置:开头的 BOM、注释、@charset、@layer 声明(不带大括号的)、@import 之后(@import 必须在最前面),接在那一行后面。
|
|
119
|
+
* @import 的网址可能不带引号、里面有 ;(Google Fonts css2 的 wght@400;700),url(…) 整个跳过
|
|
120
|
+
*/
|
|
121
|
+
function cssInsertAt(css) {
|
|
122
|
+
const re = /\s*(?:\/\*[\s\S]*?\*\/|@charset\b[^;]*;|@layer\b[^;{}]*;|@import\b(?:url\(\s*(?:"[^"]*"|'[^']*'|[^)"']*)\s*\)|"[^"]*"|'[^']*'|(?!url\()[^;'"])*;)/y
|
|
123
|
+
const bom = css.charCodeAt(0) === 0xfeff ? 1 : 0
|
|
124
|
+
let at = bom
|
|
125
|
+
for (;;) {
|
|
126
|
+
re.lastIndex = at
|
|
127
|
+
if (!re.exec(css)) break
|
|
128
|
+
at = re.lastIndex
|
|
129
|
+
}
|
|
130
|
+
if (at === bom) return bom
|
|
131
|
+
const nlAt = css.indexOf('\n', at)
|
|
132
|
+
return nlAt === -1 || css.slice(at, nlAt).trim() ? at : nlAt + 1
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const blank = (m) => m.replace(/[^\n]/g, ' ')
|
|
136
|
+
const STYLE_TAG = /<style\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi // 属性值里的 > 不算结束(media="(width >= 900px)")
|
|
137
|
+
const WRAP_ATTR = 'data-dsh-fonts' // 设计台自己加的那个 <style>(页面里没有对整个屏幕生效的 <style> 时)
|
|
138
|
+
|
|
139
|
+
/** HTML 里所有真的 <style> 开头标签(注释、脚本里的不算):[{ index, tag, screen: 对屏幕整个生效(没写 media、all、screen) }] */
|
|
140
|
+
function styleTags(html) {
|
|
141
|
+
// <noscript> 里的是关了脚本才用的备用样式,不算
|
|
142
|
+
const masked = html.replace(/<!--[\s\S]*?-->/g, blank).replace(/<(script|noscript)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, blank)
|
|
143
|
+
const out = []
|
|
144
|
+
STYLE_TAG.lastIndex = 0
|
|
145
|
+
for (let m; (m = STYLE_TAG.exec(masked));) {
|
|
146
|
+
const media = /\smedia\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(m[0])
|
|
147
|
+
const v = media ? (media[1] ?? media[2] ?? media[3]).trim().toLowerCase() : ''
|
|
148
|
+
out.push({ index: m.index, tag: m[0], screen: !v || v === 'all' || v === 'screen' })
|
|
149
|
+
}
|
|
150
|
+
return out
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
154
|
+
const famRes = new Map()
|
|
155
|
+
/** 文字里写没写这个字体名:带引号的,或者不带引号、前后是字体栈的分隔(var(--x, Inter)、style="font-family: Inter" 都算;Inter 不算 pointer、interface 里的) */
|
|
156
|
+
export function namesFamily(text, family) {
|
|
157
|
+
let re = famRes.get(family)
|
|
158
|
+
if (!re) {
|
|
159
|
+
const words = family.trim().split(/\s+/).map(escRe).join('\\s+')
|
|
160
|
+
re = new RegExp(`["']\\s*${words}\\s*["']|(?:^|[\\s,:(])${words}(?=\\s*(?:[,;!})"']|$))`, 'im')
|
|
161
|
+
famRes.set(family, re)
|
|
162
|
+
}
|
|
163
|
+
return re.test(String(text || ''))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 文字里(那段以外、注释以外)写着名字的字体库 id */
|
|
167
|
+
export function libIdsNamed(text, index) {
|
|
168
|
+
const rest = stripFontBlock(String(text || '')).replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
169
|
+
return index ? index.fonts.filter((f) => namesFamily(rest, f.family)).map((f) => f.id) : []
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* 那段改成:原来记着的 + add,再去掉 drop 里(这次被换走、整套设计都不再写它名字的)且这个文件里也不写它名字的。没变给 null
|
|
174
|
+
* isHtml:放进第一个对屏幕整个生效的 <style>;只有按尺寸 / 打印的 <style> 时在前面加一个设计台自己的;一个 <style> 都没有给 null(不自己加:只许外链样式的页面会悄悄拦掉)
|
|
175
|
+
*/
|
|
176
|
+
export function syncFontBlock(text, add, index, { prefix = FONT_DIR, isHtml = false, drop = [] } = {}) {
|
|
177
|
+
const src = String(text)
|
|
178
|
+
const cur = fontBlockIds(src)
|
|
179
|
+
const all = [...new Set([...cur, ...add])]
|
|
180
|
+
const named = new Set(drop.length ? libIdsNamed(src, index) : [])
|
|
181
|
+
const want = all.filter((id) => add.includes(id) || !drop.includes(id) || named.has(id))
|
|
182
|
+
const fonts = want.map((id) => index.fonts.find((f) => f.id === id)).filter(Boolean)
|
|
183
|
+
const nl = /\r\n/.test(src) ? '\r\n' : '\n'
|
|
184
|
+
const block = fontBlock(fonts, prefix, nl)
|
|
185
|
+
const had = BLOCK_RE.test(src)
|
|
186
|
+
BLOCK_RE.lastIndex = 0
|
|
187
|
+
let body = src.replace(BLOCK_RE, '')
|
|
188
|
+
// 设计台自己加的 <style> 空了就拿掉
|
|
189
|
+
if (isHtml) body = body.replace(new RegExp(`<style\\b[^>]*\\b${WRAP_ATTR}\\b[^>]*>\\s*</style\\s*>(?:\\r?\\n)?`, 'gi'), '')
|
|
190
|
+
let out
|
|
191
|
+
if (!block) out = body
|
|
192
|
+
else if (!isHtml) {
|
|
193
|
+
const at = cssInsertAt(body)
|
|
194
|
+
out = body.slice(0, at) + (at > 0 && !/[\n\ufeff]/.test(body[at - 1]) ? nl : '') + block + body.slice(at)
|
|
195
|
+
} else {
|
|
196
|
+
// @font-face 放在哪个 <style> 都对整页生效——前提是那个 <style> 对屏幕整个生效(media 限了尺寸、打印的,字体也跟着只在那时有)
|
|
197
|
+
const tags = styleTags(body)
|
|
198
|
+
const m = tags.find((x) => x.screen)
|
|
199
|
+
if (m) {
|
|
200
|
+
// <style> 里开头的 @import、@charset 要留在最前面(放到它们前面 @import 就不算了)
|
|
201
|
+
const start = m.index + m.tag.length
|
|
202
|
+
const close = body.slice(start).search(/<\/style\s*>/i)
|
|
203
|
+
const ins = cssInsertAt(body.slice(start, close < 0 ? body.length : start + close))
|
|
204
|
+
if (!ins) out = body.slice(0, start) + nl + block + body.slice(start).replace(/^\r?\n/, '')
|
|
205
|
+
else {
|
|
206
|
+
const at = start + ins
|
|
207
|
+
out = body.slice(0, at) + (body[at - 1] !== '\n' ? nl : '') + block + body.slice(at)
|
|
208
|
+
}
|
|
209
|
+
} else if (tags.length) {
|
|
210
|
+
// 只有按尺寸 / 打印的 <style>:在第一个前面自己加一个(带上页面 <style> 的 nonce,严格 CSP 也认)
|
|
211
|
+
const nonce = tags.map((x) => /\snonce\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(x.tag)).find(Boolean)
|
|
212
|
+
const attr = nonce ? ` nonce="${String(nonce[1] ?? nonce[2] ?? nonce[3]).replace(/["<>&]/g, '')}"` : ''
|
|
213
|
+
const at = tags[0].index
|
|
214
|
+
out = body.slice(0, at) + `<style ${WRAP_ATTR}${attr}>` + nl + block + '</style>' + nl + body.slice(at)
|
|
215
|
+
} else return null // 没有 <style>:不自己加(页面可能只许外链样式,加了会被悄悄拦掉)
|
|
216
|
+
}
|
|
217
|
+
if (out === src || (!had && !block)) return null
|
|
218
|
+
return out
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 设计目录里的文件 rel 到 fonts/ 的相对路径 */
|
|
222
|
+
export const fontPrefix = (rel) => {
|
|
223
|
+
const d = path.posix.dirname(String(rel).replace(/\\/g, '/'))
|
|
224
|
+
return d === '.' ? FONT_DIR : path.posix.relative(d, FONT_DIR)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** dsh-fonts/<id>.woff2 是字体库复制进来的就给 id,不是给 ''(版本记录不存它们:从库里随时能再拿) */
|
|
228
|
+
export function libFontIdOf(rel, index = defaultIndex()) {
|
|
229
|
+
const m = /^dsh-fonts\/([a-z0-9-]+)\.woff2$/.exec(String(rel).replace(/\\/g, '/'))
|
|
230
|
+
return m && index && index.fonts.some((f) => f.id === m[1]) ? m[1] : ''
|
|
231
|
+
}
|
|
232
|
+
export const isLibFontRel = (rel, index) => !!libFontIdOf(rel, index)
|
|
233
|
+
|
|
234
|
+
let cachedIndex
|
|
235
|
+
function defaultIndex() {
|
|
236
|
+
if (cachedIndex === undefined) cachedIndex = loadFontIndex()
|
|
237
|
+
return cachedIndex
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ── 下载、复制 ───────────────────────────────────────────────────────────────
|
|
241
|
+
|
|
242
|
+
export function createFonts({ market, index = loadFontIndex(), cacheDir = FONTS_CACHE, log = () => {}, now = Date.now } = {}) {
|
|
243
|
+
let inflight = null
|
|
244
|
+
let failedAt = -Infinity
|
|
245
|
+
let lastErr = null
|
|
246
|
+
const dirOf = () => path.join(cacheDir, index.version)
|
|
247
|
+
const fileOf = (f) => path.join(dirOf(), `${f.id}.woff2`)
|
|
248
|
+
const okFile = (f) => {
|
|
249
|
+
try { return sha256(fs.readFileSync(fileOf(f))) === f.sha256 } catch { return false }
|
|
250
|
+
}
|
|
251
|
+
const has = (f) => { try { return fs.statSync(fileOf(f)).size === f.size } catch { return false } }
|
|
252
|
+
const ready = () => index.fonts.every(has)
|
|
253
|
+
|
|
254
|
+
async function download() {
|
|
255
|
+
const files = await market.fetchPackage(index.package, index.version, {
|
|
256
|
+
cap: CAP,
|
|
257
|
+
limits: LIMITS,
|
|
258
|
+
timing: TIMING,
|
|
259
|
+
check: (list) => {
|
|
260
|
+
const by = new Map(list.map((x) => [x.path, x.data]))
|
|
261
|
+
return index.fonts.map((f) => {
|
|
262
|
+
const data = by.get(f.file)
|
|
263
|
+
if (!data || sha256(data) !== f.sha256) { const e = new Error('font mismatch'); e.code = 'mismatch'; throw e }
|
|
264
|
+
return { f, data }
|
|
265
|
+
})
|
|
266
|
+
},
|
|
267
|
+
})
|
|
268
|
+
fs.mkdirSync(dirOf(), { recursive: true })
|
|
269
|
+
for (const { f, data } of files) {
|
|
270
|
+
const tmp = `${fileOf(f)}.${process.pid}.tmp`
|
|
271
|
+
fs.writeFileSync(tmp, data)
|
|
272
|
+
fs.renameSync(tmp, fileOf(f))
|
|
273
|
+
}
|
|
274
|
+
for (const n of fs.readdirSync(cacheDir)) {
|
|
275
|
+
if (/^\d+\.\d+\.\d+/.test(n) && vcmp(n, index.version) < 0) try { fs.rmSync(path.join(cacheDir, n), { recursive: true, force: true }) } catch (e) { log(e) }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** 保证字体都在缓存里;失败抛错(err.code:off = 不联网开着) */
|
|
280
|
+
function ensure() {
|
|
281
|
+
if (ready()) return Promise.resolve()
|
|
282
|
+
if (inflight) return inflight
|
|
283
|
+
if (now() - failedAt < RETRY_MS && lastErr) return Promise.reject(lastErr)
|
|
284
|
+
inflight = download().then(
|
|
285
|
+
() => { failedAt = -Infinity; lastErr = null; inflight = null },
|
|
286
|
+
(e) => { inflight = null; log(e); if (e && e.code === 'off') { failedAt = -Infinity; lastErr = null } else { failedAt = now(); lastErr = e } throw e },
|
|
287
|
+
)
|
|
288
|
+
return inflight
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** 预览服务器用:这个 id 的缓存文件(在、大小对才给) */
|
|
292
|
+
const cached = (id) => {
|
|
293
|
+
const f = index.fonts.find((x) => x.id === id)
|
|
294
|
+
return f && has(f) ? fileOf(f) : null
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 把 fonts 复制进 <dir>/dsh-fonts/(同步;真实路径写之前核对)。已经在且内容对的不动,不对的换掉(字体库管这些文件名)。
|
|
299
|
+
* allowed(真实路径) 说这个目录能不能写;fonts 指到外面就不写。
|
|
300
|
+
*/
|
|
301
|
+
function place(dir, fonts, allowed = () => true) {
|
|
302
|
+
const denied = () => Object.assign(new Error('outside'), { code: 'link' })
|
|
303
|
+
let probe = path.resolve(dir)
|
|
304
|
+
while (!fs.existsSync(probe)) {
|
|
305
|
+
const up = path.dirname(probe)
|
|
306
|
+
if (up === probe) break
|
|
307
|
+
probe = up
|
|
308
|
+
}
|
|
309
|
+
if (!allowed(fs.realpathSync(probe))) throw denied()
|
|
310
|
+
const sub = path.join(dir, FONT_DIR)
|
|
311
|
+
fs.mkdirSync(sub, { recursive: true })
|
|
312
|
+
const realDir = fs.realpathSync(dir)
|
|
313
|
+
const realSub = fs.realpathSync(sub)
|
|
314
|
+
if (!allowed(realDir) || realSub !== path.join(realDir, FONT_DIR)) throw denied()
|
|
315
|
+
for (const f of fonts) {
|
|
316
|
+
if (!okFile(f)) {
|
|
317
|
+
try { fs.rmSync(fileOf(f), { force: true }) } catch (e) { log(e) }
|
|
318
|
+
throw Object.assign(new Error(`bad cached font ${f.id}`), { code: 'mismatch' })
|
|
319
|
+
}
|
|
320
|
+
const to = path.join(realSub, `${f.id}.woff2`)
|
|
321
|
+
let same = false
|
|
322
|
+
try {
|
|
323
|
+
const st = fs.lstatSync(to)
|
|
324
|
+
if (!st.isFile()) throw denied() // 软链接、文件夹:不往里写
|
|
325
|
+
same = st.size === f.size && sha256(fs.readFileSync(to)) === f.sha256
|
|
326
|
+
} catch (e) {
|
|
327
|
+
if (e && e.code === 'link') throw e
|
|
328
|
+
}
|
|
329
|
+
if (same) continue
|
|
330
|
+
// 临时文件独占新建(同名的东西已经在了——哪怕是软链接——就先删掉它本身再建,不顺着它写出去)
|
|
331
|
+
const tmp = `${to}.${process.pid}.tmp`
|
|
332
|
+
try {
|
|
333
|
+
fs.copyFileSync(fileOf(f), tmp, fs.constants.COPYFILE_EXCL)
|
|
334
|
+
} catch (e) {
|
|
335
|
+
if (!e || e.code !== 'EEXIST') throw e
|
|
336
|
+
fs.rmSync(tmp, { force: true })
|
|
337
|
+
fs.copyFileSync(fileOf(f), tmp, fs.constants.COPYFILE_EXCL)
|
|
338
|
+
}
|
|
339
|
+
fs.renameSync(tmp, to)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 下载 → 复制;缓存里有坏文件时重下一次 */
|
|
344
|
+
async function provide(dir, fonts, allowed) {
|
|
345
|
+
await ensure()
|
|
346
|
+
try { return place(dir, fonts, allowed) } catch (e) { if (!e || e.code !== 'mismatch') throw e }
|
|
347
|
+
await ensure()
|
|
348
|
+
return place(dir, fonts, allowed)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return { index, ready, ensure, place, provide, cached }
|
|
352
|
+
}
|
package/lib/gallery/pack.js
CHANGED
|
@@ -13,6 +13,7 @@ import path from 'node:path'
|
|
|
13
13
|
import { cleanPath, checkPack, normalizeHtml, titleOf, metaKind, message, LIMITS, capsOf, FORMAT, pctBytes, imageInfo } from './policy.js'
|
|
14
14
|
import { writeZip } from './zip.js'
|
|
15
15
|
import { isPhotoAsset } from '../photos.js'
|
|
16
|
+
import { stripFontBlock } from '../fonts.js'
|
|
16
17
|
import { decodeEntities } from './html.js'
|
|
17
18
|
|
|
18
19
|
/** 页面文本 → 去掉注释、解开各种转义、全小写,用来判断提没提到某个文件 */
|
|
@@ -273,6 +274,12 @@ export function packDesign(root, { screens, version = '', license = '', author =
|
|
|
273
274
|
data = fs.readFileSync(f.abs)
|
|
274
275
|
} catch { continue }
|
|
275
276
|
const ext = f.path.slice(f.path.lastIndexOf('.') + 1).toLowerCase()
|
|
277
|
+
// 字体库(#31):字体文件不进包(市场只收系统字体),设计台管的 @font-face 那段去掉,字体栈后面的系统字体顶上
|
|
278
|
+
if (ext === 'html' || ext === 'css') {
|
|
279
|
+
const raw = data.toString('utf8')
|
|
280
|
+
const bare = stripFontBlock(raw)
|
|
281
|
+
if (bare !== raw) { notes.push({ code: 'fontLib', x: f.path }); data = Buffer.from(bare, 'utf8') }
|
|
282
|
+
}
|
|
276
283
|
if (ext === 'html') {
|
|
277
284
|
const r = normalizeHtml(data.toString('utf8'), { file: f.path })
|
|
278
285
|
if (r.changes.length) notes.push(...r.changes)
|
package/lib/handoff.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { PHOTO_PREFIX, isPhotoAsset } from './photos.js'
|
|
13
|
+
import { isLibFontRel, loadFontIndex } from './fonts.js'
|
|
13
14
|
import fs from 'node:fs'
|
|
14
15
|
import os from 'node:os'
|
|
15
16
|
import path from 'node:path'
|
|
@@ -689,6 +690,12 @@ export function handoffMd({ root, rows, kind, size, framework, dest, project, sy
|
|
|
689
690
|
lines.push(assets.length ? `- ${assets.slice(0, 30).map((a) => `\`${a}\``).join('、')}${assets.length > 30 ? ' …' : ''}:照原样复制进项目的静态资源目录(${mini ? (uni ? `\`${at}static/\`` : taro ? `\`${at}assets/\`` : `\`${at}images/\` 之类`) : 'public/ 或 src/assets/'})` : '- 没有单独的图片、字体文件(图形都写在 HTML / SVG 里)。')
|
|
690
691
|
const aiPhotos = assets.filter((x) => isPhotoAsset(x))
|
|
691
692
|
if (aiPhotos.length) lines.push(`- 文件名带 \`${PHOTO_PREFIX}\` 的 ${aiPhotos.length} 张是 AI 生成的示意图:先照常接上,做完提醒用户上线前换成真实照片。`)
|
|
693
|
+
const libFonts = assets.filter((x) => isLibFontRel(x))
|
|
694
|
+
if (libFonts.length) {
|
|
695
|
+
const idx = loadFontIndex()
|
|
696
|
+
const names = libFonts.map((x) => { const id = path.posix.basename(x, '.woff2'); const f = idx && idx.fonts.find((y) => y.id === id); return f ? `${f.zh}(${f.source})` : id })
|
|
697
|
+
lines.push(`- \`dsh-fonts/\` 里的 ${libFonts.length} 款是设计台字体库的字体(SIL OFL 1.1,可商用;中文只裁了常用 6763 字的网页版):先照原样接上(样式里的 @font-face 跟着搬,路径按新位置改),提醒用户上线前可以换官方完整版:${names.join(';')}。`)
|
|
698
|
+
}
|
|
692
699
|
if (mini) lines.push(`- 小程序主包不能超过 2MB:大图放服务器用网址;字体文件要用 \`${api}.loadFontFace\` 从网址加载,加载不了就用系统字体。`)
|
|
693
700
|
lines.push('')
|
|
694
701
|
|
package/lib/history.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import fs from 'node:fs'
|
|
11
11
|
import path from 'node:path'
|
|
12
12
|
import crypto from 'node:crypto'
|
|
13
|
+
import { isLibFontRel } from './fonts.js'
|
|
13
14
|
|
|
14
15
|
const KEEP_EXT = /\.(html?|css|m?js|json|svg|txt|md|png|jpe?g|webp|gif|avif|ico|woff2?|ttf|otf)$/i
|
|
15
16
|
const SKIP_DIR = /^(node_modules|\.git|\.next|\.cache|\.turbo|dist|build|exports|refs|handoff)$|^\./
|
|
@@ -62,6 +63,7 @@ export function collect(root) {
|
|
|
62
63
|
continue
|
|
63
64
|
}
|
|
64
65
|
if (!d.isFile() || d.name.startsWith('.') || !KEEP_EXT.test(d.name)) continue
|
|
66
|
+
if (isLibFontRel(r)) continue // 字体库复制进来的字体(#31):库里随时能再拿,不占版本记录的空间
|
|
65
67
|
let st
|
|
66
68
|
try { st = fs.statSync(abs) } catch { continue }
|
|
67
69
|
if (st.size > MAX_FILE) continue
|
package/lib/htmlpack.js
CHANGED
|
@@ -21,6 +21,8 @@ import { MOCK_FILE, mockExpr, mockOfBuf, mockRuntime } from './mock.js'
|
|
|
21
21
|
export const PACK_ORIGIN = 'https://ddp-pack.invalid'
|
|
22
22
|
export const PACK_MAX = 150 * 1024 * 1024 // 整个文件的上限(字符数):再大浏览器打开就很慢了
|
|
23
23
|
export const PACK_SCREENS = 1000 // 画布只显示 60 屏,导出要全部(#29:有人的设计 400 多屏);真正拦的是 PACK_MAX
|
|
24
|
+
// 一屏内联的上限:字体库两款中文就有 6 MB 多(#31),再加一张大图远程看的 12 MB 不够;整个文件还有 PACK_MAX 兜着
|
|
25
|
+
const SCREEN_MAX = 48 * 1024 * 1024
|
|
24
26
|
const ASSET_MIN = 2048 // 这么长以上的 data: 地址单独存一份(几屏共用的只存一次)
|
|
25
27
|
|
|
26
28
|
// ── 和 client.js 同一份数(测试比着)────────────────────────────────────────
|
|
@@ -111,6 +113,8 @@ function navScript(C, ST) {
|
|
|
111
113
|
const de = document.documentElement
|
|
112
114
|
for (const [k, v] of Object.entries((C.tweak && C.tweak.vars) || {})) { try { de.style.setProperty(k, String(v), 'important') } catch { /* 不认的值 */ } }
|
|
113
115
|
for (const [k, v] of Object.entries((C.tweak && C.tweak.attrs) || {})) { try { if (v == null || v === false) de.removeAttribute(k); else de.setAttribute(k, String(v)) } catch { /* 不认的名字 */ } }
|
|
116
|
+
const fonts = (C.tweak && C.tweak.fonts) || []
|
|
117
|
+
if (fonts.length) style(fonts.map((f) => `@font-face{font-family:"${f.family}";src:url("${f.url}") format("woff2");font-weight:${f.w};font-display:swap}`).join(''))
|
|
114
118
|
// 一页多状态(#30):播放器放这一屏时给的状态(order.html?state=paid)写在 <html data-state> 上
|
|
115
119
|
const STATE_RE = /^[A-Za-z0-9_-]{1,32}$/
|
|
116
120
|
/** 这页 <meta name="dsh-states"> 里写了哪几个状态(不到两个当没写) */
|
|
@@ -703,20 +707,37 @@ body.compact #menu{display:block;position:fixed;left:50%;top:calc(4px + env(safe
|
|
|
703
707
|
@media (max-width:560px){#bar .ttl{display:none}#bar .end{flex:none}}
|
|
704
708
|
`
|
|
705
709
|
|
|
710
|
+
/**
|
|
711
|
+
* 外观面板里选了、还没存的字体库字体(#31):[{ family, w, url: data: 地址 }](libFont(id) → { family, weights, data } | null)。
|
|
712
|
+
* 写进每屏的配置里,打包时和别的 data: 地址一样整套只放一份
|
|
713
|
+
*/
|
|
714
|
+
function tweakFonts(ids, libFont) {
|
|
715
|
+
const out = []
|
|
716
|
+
for (const id of Array.isArray(ids) ? ids.slice(0, 8) : []) {
|
|
717
|
+
let f = null
|
|
718
|
+
try { f = typeof id === 'string' ? libFont(id) : null } catch { f = null }
|
|
719
|
+
if (!f || !/^[A-Za-z0-9 ]{1,40}$/.test(f.family) || !Buffer.isBuffer(f.data)) continue
|
|
720
|
+
const w = Array.isArray(f.weights) && f.weights.length === 2 ? `${f.weights[0] | 0} ${f.weights[1] | 0}` : '100 900'
|
|
721
|
+
out.push({ family: f.family, w, url: `data:font/woff2;base64,${f.data.toString('base64')}` })
|
|
722
|
+
}
|
|
723
|
+
return out
|
|
724
|
+
}
|
|
725
|
+
|
|
706
726
|
/**
|
|
707
727
|
* 打一份演示包。
|
|
708
728
|
* screens:[{ key, label, top }](top:顶栏是深色,外壳上的胶囊 / 窗口按钮画白的)
|
|
709
729
|
* dark:右侧栏开着「深色」;scheme:右侧栏当时的系统深浅色('dark' / 'light'),没开「深色」时页面按它显示
|
|
710
730
|
* read(rel):设计目录里的文件(Buffer,读不到 null);strictOf(page):这屏是不是别人做的(加硬规矩:只跑我们的脚本)
|
|
711
|
-
*
|
|
731
|
+
* libFont(id):外观面板里选了还没存的字体库字体 → { family, weights, data }
|
|
732
|
+
* 回 { html, missing: [没读到的屏], count, skipped: [有、但太大没放进去的文件] }
|
|
712
733
|
*/
|
|
713
|
-
export function buildPack({ screens, read, bigOf = null, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false }) {
|
|
734
|
+
export function buildPack({ screens, read, bigOf = null, strictOf = () => false, kind, w, h, os = '', dark = false, scheme = 'light', tweak = null, title = '', lang = 'zh', fit = false, libFont = () => null }) {
|
|
714
735
|
kind = FRAME[kind] ? kind : 'web'
|
|
715
736
|
const S = STRINGS[lang === 'en' ? 'en' : 'zh']
|
|
716
737
|
const token = 'ddpA' + crypto.randomBytes(5).toString('hex') + '_'
|
|
717
738
|
const storeMark = `/*ddpS${token}*/null`
|
|
718
739
|
const nonce = crypto.randomBytes(16).toString('base64')
|
|
719
|
-
const navCfg = { origin: PACK_ORIGIN, sel: LINK_SEL, js: LINK_JS.source, pages: !!FIXED[kind], tweak: tweak && typeof tweak === 'object' ? { vars: tweak.vars || {}, attrs: tweak.attrs || {} } : null }
|
|
740
|
+
const navCfg = { origin: PACK_ORIGIN, sel: LINK_SEL, js: LINK_JS.source, pages: !!FIXED[kind], tweak: tweak && typeof tweak === 'object' ? { vars: tweak.vars || {}, attrs: tweak.attrs || {}, fonts: tweakFonts(tweak.fonts, libFont) } : null }
|
|
720
741
|
const script = (src, strict) => `<script${strict ? ` nonce="${nonce}"` : ''}>${src.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--')}</script>`
|
|
721
742
|
const shimSrc = `(${storeShim})(${storeMark});`
|
|
722
743
|
const stateMark = `/*ddpT${token}*/''` // 放一屏时换成这屏的状态(#30)
|
|
@@ -742,6 +763,8 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
742
763
|
const parts = []
|
|
743
764
|
const list = []
|
|
744
765
|
const missing = []
|
|
766
|
+
const skipped = new Set() // 有、但太大放不进去的文件(单个超过 12 MB、一屏加起来超过 SCREEN_MAX):导出照样出,但要告诉用户缺了哪些
|
|
767
|
+
const readPage = (rel) => { const b = read(rel); if (!b && bigOf && bigOf(rel)) skipped.add(rel); return b }
|
|
745
768
|
let total = mk ? JSON.stringify(mk.data).length + JSON.stringify(mockAssets).length : 0
|
|
746
769
|
for (const s of screens.slice(0, PACK_SCREENS)) {
|
|
747
770
|
const page = read(s.key)
|
|
@@ -751,7 +774,9 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
751
774
|
const base = PACK_ORIGIN + '/' + s.key.split('/').map(encodeURIComponent).join('/')
|
|
752
775
|
let out = bundle(strict ? defang(text) : text, {
|
|
753
776
|
key: s.key,
|
|
754
|
-
read,
|
|
777
|
+
read: readPage,
|
|
778
|
+
max: SCREEN_MAX,
|
|
779
|
+
onSkip: (rel) => skipped.add(rel),
|
|
755
780
|
base,
|
|
756
781
|
lead: (strict ? strictMeta(nonce) : '') + script(shimSrc + mockSrc + navSrc(strict), strict),
|
|
757
782
|
tail: script(schemeSrc, strict),
|
|
@@ -799,5 +824,5 @@ export function buildPack({ screens, read, bigOf = null, strictOf = () => false,
|
|
|
799
824
|
+ assets.map((a, i) => `<script type="application/json" id="ddp-a-${i}">${jsonTag(a)}</script>`).join('')
|
|
800
825
|
+ `<script>(${player})()</script>`
|
|
801
826
|
+ '</body></html>\n'
|
|
802
|
-
return { html, missing, count: list.length }
|
|
827
|
+
return { html, missing, count: list.length, skipped: [...skipped] }
|
|
803
828
|
}
|