@joplo-app/server 0.2.0 → 0.2.2

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/dist/build.js CHANGED
@@ -20,6 +20,7 @@ import { build as viteBuild, createServer } from 'vite';
20
20
  import { JoploError } from '@joplo-app/core';
21
21
  import { compileProject } from "./project.js";
22
22
  import { joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
23
+ import { subsetSiteFonts } from "./site-fonts.js";
23
24
  /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级与镜头属于演示,保留(D43)。 */
24
25
  export function publishPayload(project, home) {
25
26
  const { rules: _r, cases: _c, issues: _i, ...rest } = project;
@@ -133,6 +134,8 @@ export async function buildSite(opts) {
133
134
  for (const rel of inlined)
134
135
  fs.rmSync(path.join(staging, rel));
135
136
  fs.writeFileSync(path.join(staging, 'index.html'), html.replace(/<title>[^<]*<\/title>/i, () => `<title>${escapeHtml(project.name)} · Joplo</title>`));
137
+ // D59: scan every staged text artifact, then retain only font subsets its content needs.
138
+ subsetSiteFonts(staging, web);
136
139
  // 4. 写入目标目录
137
140
  if (fs.existsSync(outDir))
138
141
  fs.rmSync(outDir, { recursive: true, force: true });
@@ -0,0 +1,10 @@
1
+ /** D59: pure font subsetting policy; uncertain CSS always survives. */
2
+ export declare function parseUnicodeRange(spec: string): [number, number][] | null;
3
+ export declare function rangeIntersects(spec: string, points: ReadonlySet<number>): boolean;
4
+ /** Include both literal text and encodings left by JS/JSON, CSS content and HTML. */
5
+ export declare function collectCodepoints(text: string): Set<number>;
6
+ export declare function pruneFontCss(css: string, points: ReadonlySet<number>): {
7
+ css: string;
8
+ keptFiles: string[];
9
+ removedFiles: string[];
10
+ };
@@ -0,0 +1,130 @@
1
+ /** D59: pure font subsetting policy; uncertain CSS always survives. */
2
+ export function parseUnicodeRange(spec) {
3
+ const out = [];
4
+ for (const part of spec.split(',')) {
5
+ const m = /^U\+([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?$|^U\+([0-9a-f]*\?+)$/i.exec(part.trim());
6
+ if (!m)
7
+ return null;
8
+ if (m[3] && m[3].length > 6)
9
+ return null;
10
+ const lo = Number.parseInt(m[3] ? m[3].replaceAll('?', '0') : m[1], 16);
11
+ const hi = Number.parseInt(m[3] ? m[3].replaceAll('?', 'f') : m[2] ?? m[1], 16);
12
+ if (lo > hi || hi > 0x10ffff)
13
+ return null;
14
+ out.push([lo, hi]);
15
+ }
16
+ return out;
17
+ }
18
+ export function rangeIntersects(spec, points) {
19
+ const ranges = parseUnicodeRange(spec);
20
+ return ranges === null || ranges.some(([lo, hi]) => { for (const cp of points)
21
+ if (cp >= lo && cp <= hi)
22
+ return true; return false; });
23
+ }
24
+ /** Include both literal text and encodings left by JS/JSON, CSS content and HTML. */
25
+ export function collectCodepoints(text) {
26
+ const points = new Set();
27
+ const add = (s) => { for (const c of s)
28
+ points.add(c.codePointAt(0)); };
29
+ add(text);
30
+ add(text.replace(/\\u\{([\da-f]{1,6})\}|\\u([\da-f]{4})|\\x([\da-f]{2})/gi, (raw, astral, unit, byte) => {
31
+ const cp = Number.parseInt(astral ?? unit ?? byte, 16);
32
+ return cp <= 0x10ffff ? String.fromCodePoint(cp) : raw;
33
+ }));
34
+ for (const m of text.matchAll(/\\([\da-f]{1,6})(?:\s)?|&#(?:x([\da-f]+)|(\d+));?/gi)) {
35
+ const cp = Number.parseInt(m[1] ?? m[2] ?? m[3], m[3] ? 10 : 16);
36
+ if (cp <= 0x10ffff)
37
+ points.add(cp);
38
+ }
39
+ return points;
40
+ }
41
+ /** Token boundaries ignore strings/comments, including braces in quoted font names. */
42
+ function faceSpans(css) {
43
+ const spans = [];
44
+ let start = -1, depth = 0, quote = '';
45
+ for (let i = 0; i < css.length; i++) {
46
+ const c = css[i];
47
+ if (quote) {
48
+ if (c === '\\')
49
+ i++;
50
+ else if (c === quote)
51
+ quote = '';
52
+ continue;
53
+ }
54
+ if (c === '/' && css[i + 1] === '*') {
55
+ const end = css.indexOf('*/', i + 2);
56
+ if (end < 0)
57
+ break;
58
+ i = end + 1;
59
+ continue;
60
+ }
61
+ if (c === '"' || c === "'") {
62
+ quote = c;
63
+ continue;
64
+ }
65
+ if (start < 0 && c === '@') {
66
+ const match = /^@font-face\s*\{/i.exec(css.slice(i));
67
+ if (match) {
68
+ start = i;
69
+ depth = 1;
70
+ i += match[0].length - 1;
71
+ }
72
+ }
73
+ else if (start >= 0) {
74
+ if (c === '{')
75
+ depth++;
76
+ if (c === '}' && --depth === 0) {
77
+ spans.push([start, i + 1]);
78
+ start = -1;
79
+ }
80
+ }
81
+ }
82
+ return spans;
83
+ }
84
+ /** Read descriptors only at declaration boundaries, never inside strings or url(). */
85
+ function unicodeRange(rule) {
86
+ const body = rule.slice(rule.indexOf('{') + 1, -1).replace(/\/\*[\s\S]*?\*\//g, '');
87
+ const ranges = [];
88
+ let start = 0, quote = '', depth = 0;
89
+ for (let i = 0; i <= body.length; i++) {
90
+ const c = body[i];
91
+ if (quote) {
92
+ if (c === '\\')
93
+ i++;
94
+ else if (c === quote)
95
+ quote = '';
96
+ continue;
97
+ }
98
+ if (c === '"' || c === "'") {
99
+ quote = c;
100
+ continue;
101
+ }
102
+ if (c === '{' || c === '}')
103
+ return null;
104
+ if (c === '(')
105
+ depth++;
106
+ if (c === ')')
107
+ depth--;
108
+ if (depth === 0 && (c === ';' || i === body.length)) {
109
+ const descriptor = /^\s*unicode-range\s*:\s*(.*?)\s*$/i.exec(body.slice(start, i));
110
+ if (descriptor)
111
+ ranges.push(descriptor[1]);
112
+ start = i + 1;
113
+ }
114
+ }
115
+ return ranges.length === 1 ? ranges[0] : null;
116
+ }
117
+ export function pruneFontCss(css, points) {
118
+ const kept = new Set(), removed = new Set();
119
+ let output = '', cursor = 0;
120
+ for (const [start, end] of faceSpans(css)) {
121
+ const rule = css.slice(start, end);
122
+ const range = unicodeRange(rule);
123
+ const keep = range === null || rangeIntersects(range, points);
124
+ for (const m of rule.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^\s)]+))\s*\)/gi))
125
+ (keep ? kept : removed).add(m[1] ?? m[2] ?? m[3]);
126
+ output += css.slice(cursor, start) + (keep ? rule : '');
127
+ cursor = end;
128
+ }
129
+ return { css: output + css.slice(cursor), keptFiles: [...kept].sort(), removedFiles: [...removed].filter((f) => !kept.has(f)).sort() };
130
+ }
@@ -70,10 +70,10 @@
70
70
  }
71
71
 
72
72
  // 4. 字体
73
- // 主题用到手写字体时(--jp-font 含 Excalifont)检查它们已加载
74
- if (/Excalifont|Xiaolai/.test(getComputedStyle(stage).fontFamily)) {
75
- const text = stage.innerText || '中文';
76
- if (!document.fonts.check('16px "Joplo Excalifont"', text) || !document.fonts.check('16px "Joplo Xiaolai"', text)) warnings.push('Fonts not loaded: Hand-drawn fonts (Excalifont / Xiaolai) are not ready; the screenshot may use fallback fonts');
73
+ // Check the selected stack, including author themes and system fallbacks.
74
+ const family = getComputedStyle(stage).fontFamily;
75
+ if (!document.fonts.check(`16px ${family}`, stage.innerText || 'Aa')) {
76
+ warnings.push('Fonts not loaded: The selected font is not ready; the screenshot may use fallback fonts');
77
77
  }
78
78
  const failed = Array.from(document.fonts).filter((f) => f.status === 'error');
79
79
  if (failed.length) warnings.push(`Fonts not loaded: ${failed.length} font files failed to load (${failed[0].family})`);
@@ -0,0 +1,3 @@
1
+ import type { WebAssets } from './web-assets.js';
2
+ /** Runs after IR/JS inlining and author CSS compilation in both source and dist mode. */
3
+ export declare function subsetSiteFonts(staging: string, web: WebAssets): void;
@@ -0,0 +1,64 @@
1
+ import fs from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { collectCodepoints, pruneFontCss } from "./font-subsets.js";
5
+ function files(dir) {
6
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? files(path.join(dir, e.name)) : [path.join(dir, e.name)]);
7
+ }
8
+ /** Runs after IR/JS inlining and author CSS compilation in both source and dist mode. */
9
+ export function subsetSiteFonts(staging, web) {
10
+ const all = files(staging);
11
+ const points = new Set();
12
+ const decoder = new TextDecoder('utf-8', { fatal: true });
13
+ for (const file of all) {
14
+ let text;
15
+ try {
16
+ text = decoder.decode(fs.readFileSync(file));
17
+ }
18
+ catch {
19
+ continue;
20
+ }
21
+ if (text.includes('\0'))
22
+ continue;
23
+ for (const cp of collectCodepoints(text))
24
+ points.add(cp);
25
+ }
26
+ const retained = new Set();
27
+ const renamed = new Map();
28
+ let cssText = '';
29
+ for (const file of all.filter((f) => f.endsWith('.css'))) {
30
+ const original = fs.readFileSync(file, 'utf8');
31
+ const result = pruneFontCss(original, points);
32
+ if (result.css !== original) {
33
+ const hash = createHash('sha256').update(result.css).digest('hex').slice(0, 12);
34
+ const target = file.slice(0, -4) + `-font-${hash}.css`;
35
+ fs.writeFileSync(target, result.css);
36
+ fs.rmSync(file);
37
+ renamed.set(file, target);
38
+ }
39
+ cssText += result.css;
40
+ // Also preserve URLs in unfamiliar/unclosed rules that the conservative parser left untouched.
41
+ for (const m of result.css.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^\s)]+))\s*\)/gi)) {
42
+ retained.add(path.resolve(path.dirname(file), m[1] ?? m[2] ?? m[3]));
43
+ }
44
+ }
45
+ // The original Vite hash predates pruning. A fresh URL prevents stale CSS from requesting deleted subsets.
46
+ for (const file of all.filter((f) => f.endsWith('.html'))) {
47
+ const html = fs.readFileSync(file, 'utf8').replace(/(<link\b[^>]*?\bhref=["'])([^"']+)(["'])/gi, (raw, before, url, after) => {
48
+ const target = renamed.get(path.resolve(path.dirname(file), url));
49
+ return target ? `${before}./${path.relative(path.dirname(file), target).split(path.sep).join('/')}${after}` : raw;
50
+ });
51
+ fs.writeFileSync(file, html);
52
+ }
53
+ // Resolve all stylesheets together: a file shared by two rules or CSS assets must survive.
54
+ for (const file of all)
55
+ if (file.endsWith('.woff2') && !retained.has(file))
56
+ fs.rmSync(file);
57
+ const licenses = web.mode === 'source' ? path.join(web.webDir, 'src/fonts') : path.join(web.webDir, 'dist/fonts');
58
+ for (const [family, license] of [['Joplo Excalifont', 'OFL.txt'], ['Joplo Marker Gothic', 'OFL-MarkerGothic.txt']]) {
59
+ if (!cssText.includes(family))
60
+ continue;
61
+ fs.mkdirSync(path.join(staging, 'fonts'), { recursive: true });
62
+ fs.copyFileSync(path.join(licenses, license), path.join(staging, 'fonts', license));
63
+ }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.0",
19
- "@joplo-app/kit": "0.2.0",
20
- "@joplo-app/web": "0.2.0",
18
+ "@joplo-app/core": "0.2.2",
19
+ "@joplo-app/kit": "0.2.2",
20
+ "@joplo-app/web": "0.2.2",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "tailwindcss": "4.3.4",
23
23
  "vite": "8.3.5",