@forgewp/compiler 0.4.2 → 0.4.4
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.md +70 -3
- package/bin/add.js +30 -15
- package/bin/analyze.js +66 -1
- package/bin/cli.js +149 -70
- package/bin/doctor.js +21 -12
- package/bin/export.js +69 -20
- package/bin/fresh.js +6 -1
- package/bin/i18n-extract.js +3 -10
- package/bin/i18n-translate.js +15 -24
- package/bin/make-block.js +24 -0
- package/bin/make-editable.js +166 -0
- package/bin/make-form.js +131 -0
- package/bin/make-island.js +11 -0
- package/bin/make-loop.js +147 -0
- package/bin/make-mail.js +27 -0
- package/bin/make-page.js +83 -0
- package/bin/make-post-type.js +68 -29
- package/bin/make-sandbox.js +609 -0
- package/bin/make-section.js +221 -0
- package/bin/make-shell.js +375 -0
- package/bin/repair.js +14 -26
- package/bin/seed.js +119 -0
- package/bin/sync-routes.js +107 -85
- package/lib/adapters/html-adapter.js +13 -3
- package/lib/adapters/stub-adapter.js +10 -2
- package/lib/add-component.js +153 -92
- package/lib/asset-loader.js +333 -1
- package/lib/assets/asset-graph.js +432 -0
- package/lib/assets/asset-pipeline.js +125 -0
- package/lib/assets/diagnostics-report.js +345 -0
- package/lib/assets/external-fetcher.js +173 -0
- package/lib/assets/font-orchestrator.js +348 -0
- package/lib/assets/font-usage-scanner.js +242 -0
- package/lib/assets/image-optimizer.js +229 -0
- package/lib/assets/index.js +51 -0
- package/lib/assets/preload-generator.js +70 -0
- package/lib/assets/public-url.js +153 -0
- package/lib/block-authoring-help.js +11 -0
- package/lib/blocks/ast-parser.js +67 -0
- package/lib/blocks/discover-blocks.js +146 -0
- package/lib/blocks/editor-scope.js +733 -0
- package/lib/blocks/editor-transpiler.js +1229 -0
- package/lib/blocks/index.js +2838 -0
- package/lib/blocks/php-transpiler.js +4928 -0
- package/lib/blocks/scanner.js +1487 -0
- package/lib/blocks/shared-utils.js +290 -0
- package/lib/blocks/source-sanitize.js +1449 -0
- package/lib/blueprints.js +77 -5
- package/lib/build-assets.js +38 -33
- package/lib/collect-page-template-routes.js +102 -0
- package/lib/collect-static-routes.js +175 -0
- package/lib/diagnostics.js +58 -33
- package/lib/export-theme.js +84 -5
- package/lib/extract-template-content.js +90 -0
- package/lib/forms-preview.js +42 -0
- package/lib/functions/cpt-routing.js +69 -0
- package/lib/functions/forms.js +2461 -0
- package/lib/functions/hydration-enqueuer.js +400 -0
- package/lib/functions/index.js +1623 -0
- package/lib/functions/load-menus.js +112 -0
- package/lib/functions/load-translations.js +148 -0
- package/lib/functions/rest-endpoints.js +2923 -0
- package/lib/functions/routing.js +765 -0
- package/lib/functions/seed-mock-data.js +392 -0
- package/lib/functions/seed-products.js +481 -0
- package/lib/functions/settings-page.js +273 -0
- package/lib/functions/theme-setup.js +494 -0
- package/lib/generate-theme.js +2076 -303
- package/lib/hydration/editable-schemas.js +332 -0
- package/lib/hydration/enter-hidden-initial.js +65 -0
- package/lib/hydration/form-schemas.js +227 -0
- package/lib/hydration/index.js +12 -0
- package/lib/hydration/is-interactive.js +951 -0
- package/lib/hydration/island-split.js +1231 -0
- package/lib/hydration/islands-scanner.js +599 -0
- package/lib/hydration/resolve-island-chunk.js +103 -0
- package/lib/hydration/resolve-island-component.js +52 -0
- package/lib/hydration/rollup-inputs.js +81 -0
- package/lib/hydration/root-class-extractor.js +220 -0
- package/lib/hydration/scan-app-providers.js +154 -0
- package/lib/hydration/static-lint.js +382 -0
- package/lib/hydration/transform.js +257 -0
- package/lib/hydration/uses-block-area.js +49 -0
- package/lib/hydration/utils.js +119 -0
- package/lib/i18n/translation-cache.js +141 -0
- package/lib/icon-registry.js +72 -0
- package/lib/index.d.ts +324 -8
- package/lib/index.js +3 -2
- package/lib/load-config.js +338 -144
- package/lib/mail-templates.js +37 -0
- package/lib/markup-processor.js +483 -92
- package/lib/node-runtime.js +7 -0
- package/lib/page-config-plugin.js +84 -0
- package/lib/php-builders.js +383 -42
- package/lib/react-adapter.js +1053 -246
- package/lib/registration-metadata.js +11 -0
- package/lib/render-theme.mts +1410 -543
- package/lib/route-layout.js +76 -0
- package/lib/template-discovery.js +58 -0
- package/lib/theme-compatibility.js +32 -0
- package/lib/validate-export.js +51 -2
- package/lib/validate.js +27 -5
- package/lib/virtual-plugin.js +319 -0
- package/lib/walkthrough.md +26 -0
- package/package.json +17 -5
- package/templates/PresetsStyle.tsx +1 -1
- package/templates/auth/cms/email-logs.json +9 -0
- package/templates/auth/cms/menus.json +11 -0
- package/templates/auth/cms/mock-data.json +123 -0
- package/templates/auth/cms/roles.json +7 -0
- package/templates/auth/cms/sessions.json +1 -0
- package/templates/auth/cms/site-settings.json +28 -0
- package/templates/auth/cms/translations.json +4 -0
- package/templates/auth/cms/users.json +46 -0
- package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
- package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
- package/templates/auth/components/login-form-wrapper.tsx +300 -0
- package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
- package/templates/auth/components/signup-form-wrapper.tsx +257 -0
- package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
- package/templates/auth/pages/DashboardPage.tsx +12 -0
- package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
- package/templates/auth/pages/LoginPage.tsx +11 -0
- package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
- package/templates/auth/pages/SignUpPage.tsx +11 -0
- package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
- package/templates/auth/ui/button.tsx +57 -0
- package/templates/auth/ui/card.tsx +76 -0
- package/templates/auth/ui/field.tsx +242 -0
- package/templates/auth/ui/input.tsx +22 -0
- package/templates/auth/ui/label.tsx +24 -0
- package/templates/auth/ui/separator.tsx +31 -0
- package/templates/forgewp-config.ts +70 -3
- package/templates/menus.json +12 -10
- package/templates/mock-data.json +122 -433
- package/templates/products.json +5 -0
- package/templates/roles.json +7 -0
- package/templates/sessions.json +1 -0
- package/templates/users.json +38 -0
- package/templates/wordpress.tsx +1835 -1297
- package/bin/make-template.js +0 -145
- package/lib/block-compiler.js +0 -552
- package/lib/functions-builder.js +0 -2044
- package/lib/hydration-scanner.js +0 -821
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import {
|
|
5
|
+
scanFontWeightUsage,
|
|
6
|
+
detectUnusedConfiguredWeights,
|
|
7
|
+
} from './font-usage-scanner.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Modern Desktop User-Agent used to request WOFF2 format from Google Fonts API.
|
|
11
|
+
*/
|
|
12
|
+
const WOFF2_USER_AGENT =
|
|
13
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Parse Google Fonts family strings from configuration.
|
|
17
|
+
*
|
|
18
|
+
* @param {Array<string>|Object} configFonts
|
|
19
|
+
* @returns {string[]} Array of formatted family strings (e.g. ["Inter:wght@400;500;700", "Space+Grotesk:wght@500;700"])
|
|
20
|
+
*/
|
|
21
|
+
export function normalizeFontFamilies(configFonts) {
|
|
22
|
+
if (!configFonts) return [];
|
|
23
|
+
const rawList = Array.isArray(configFonts)
|
|
24
|
+
? configFonts
|
|
25
|
+
: configFonts.families || [];
|
|
26
|
+
|
|
27
|
+
return rawList
|
|
28
|
+
.map((item) => {
|
|
29
|
+
if (typeof item !== 'string') return '';
|
|
30
|
+
const trimmed = item.trim();
|
|
31
|
+
if (!trimmed) return '';
|
|
32
|
+
|
|
33
|
+
// Normalize "Inter:400,500,600,700" to "Inter:wght@400;500;600;700"
|
|
34
|
+
if (trimmed.includes(':') && !trimmed.includes('wght@')) {
|
|
35
|
+
const [name, weights] = trimmed.split(':');
|
|
36
|
+
const formattedName = name.trim().replace(/\s+/g, '+');
|
|
37
|
+
const formattedWeights = weights
|
|
38
|
+
.split(',')
|
|
39
|
+
.map((w) => w.trim())
|
|
40
|
+
.filter(Boolean)
|
|
41
|
+
.join(';');
|
|
42
|
+
return `${formattedName}:wght@${formattedWeights}`;
|
|
43
|
+
}
|
|
44
|
+
return trimmed.replace(/\s+/g, '+');
|
|
45
|
+
})
|
|
46
|
+
.filter(Boolean);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Fetch CSS from Google Fonts API with WOFF2 User-Agent.
|
|
51
|
+
*
|
|
52
|
+
* @param {string[]} families - Array of normalized family parameters
|
|
53
|
+
* @param {string} [display='swap']
|
|
54
|
+
* @returns {Promise<string>}
|
|
55
|
+
*/
|
|
56
|
+
export async function fetchGoogleFontCss(families, display = 'swap') {
|
|
57
|
+
if (!families || families.length === 0) return '';
|
|
58
|
+
|
|
59
|
+
const queryParams = families.map((f) => `family=${f}`).join('&');
|
|
60
|
+
const url = `https://fonts.googleapis.com/css2?${queryParams}&display=${display}`;
|
|
61
|
+
|
|
62
|
+
const response = await fetch(url, {
|
|
63
|
+
headers: {
|
|
64
|
+
'User-Agent': WOFF2_USER_AGENT,
|
|
65
|
+
Accept: 'text/css,*/*;q=0.1',
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
if (!response.ok) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`[ForgeWP Font Orchestrator] Google Fonts HTTP ${response.status} fetching CSS: ${url}`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return response.text();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Parse `@font-face` rules and extract font metadata and remote URLs.
|
|
80
|
+
*
|
|
81
|
+
* @param {string} css
|
|
82
|
+
* @returns {Array<Object>}
|
|
83
|
+
*/
|
|
84
|
+
export function parseFontFaceRules(css) {
|
|
85
|
+
if (!css || typeof css !== 'string') return [];
|
|
86
|
+
|
|
87
|
+
const fontFaceRegex = /@font-face\s*\{([^}]+)\}/g;
|
|
88
|
+
const rules = [];
|
|
89
|
+
let match;
|
|
90
|
+
|
|
91
|
+
while ((match = fontFaceRegex.exec(css)) !== null) {
|
|
92
|
+
const block = match[1];
|
|
93
|
+
|
|
94
|
+
const getProp = (name) => {
|
|
95
|
+
const propRegex = new RegExp(`${name}:\\s*([^;]+);`, 'i');
|
|
96
|
+
const m = block.match(propRegex);
|
|
97
|
+
return m ? m[1].trim() : '';
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const family = getProp('font-family').replace(/['"]/g, '');
|
|
101
|
+
const style = getProp('font-style') || 'normal';
|
|
102
|
+
const weight = getProp('font-weight') || '400';
|
|
103
|
+
const display = getProp('font-display') || 'swap';
|
|
104
|
+
const unicodeRange = getProp('unicode-range') || '';
|
|
105
|
+
|
|
106
|
+
const srcMatch = block.match(
|
|
107
|
+
/src:\s*url\((https:\/\/[^)]+)\)\s*format\(['"]?([^'"]+)['"]?\)/i,
|
|
108
|
+
);
|
|
109
|
+
const url = srcMatch ? srcMatch[1] : '';
|
|
110
|
+
const format = srcMatch ? srcMatch[2] : 'woff2';
|
|
111
|
+
|
|
112
|
+
if (family && url) {
|
|
113
|
+
rules.push({
|
|
114
|
+
family,
|
|
115
|
+
style,
|
|
116
|
+
weight,
|
|
117
|
+
display,
|
|
118
|
+
unicodeRange,
|
|
119
|
+
remoteUrl: url,
|
|
120
|
+
format,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return rules;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Download WOFF2 font files to local disk with caching.
|
|
130
|
+
*
|
|
131
|
+
* @param {Array<Object>} rules
|
|
132
|
+
* @param {string} outputDir
|
|
133
|
+
* @param {string} cacheDir
|
|
134
|
+
* @returns {Promise<Array<Object>>} Enriched rules with local filenames and paths
|
|
135
|
+
*/
|
|
136
|
+
export async function downloadFontFiles(rules, outputDir, cacheDir) {
|
|
137
|
+
if (!existsSync(outputDir)) {
|
|
138
|
+
mkdirSync(outputDir, { recursive: true });
|
|
139
|
+
}
|
|
140
|
+
if (cacheDir && !existsSync(cacheDir)) {
|
|
141
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const enriched = [];
|
|
145
|
+
let index = 1;
|
|
146
|
+
|
|
147
|
+
for (const rule of rules) {
|
|
148
|
+
const urlHash = crypto
|
|
149
|
+
.createHash('sha256')
|
|
150
|
+
.update(rule.remoteUrl)
|
|
151
|
+
.digest('hex')
|
|
152
|
+
.slice(0, 12);
|
|
153
|
+
const cleanFamily = rule.family.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
|
|
154
|
+
const filename = `${cleanFamily}-${rule.weight}-${rule.style}-${urlHash}.woff2`;
|
|
155
|
+
const outputPath = path.join(outputDir, filename);
|
|
156
|
+
|
|
157
|
+
let buffer = null;
|
|
158
|
+
|
|
159
|
+
// Check disk cache
|
|
160
|
+
if (cacheDir) {
|
|
161
|
+
const cachedFile = path.join(cacheDir, filename);
|
|
162
|
+
if (existsSync(cachedFile)) {
|
|
163
|
+
buffer = readFileSync(cachedFile);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (!buffer) {
|
|
168
|
+
try {
|
|
169
|
+
const response = await fetch(rule.remoteUrl, {
|
|
170
|
+
headers: { 'User-Agent': WOFF2_USER_AGENT },
|
|
171
|
+
});
|
|
172
|
+
if (!response.ok) {
|
|
173
|
+
throw new Error(`HTTP ${response.status}`);
|
|
174
|
+
}
|
|
175
|
+
const arrayBuf = await response.arrayBuffer();
|
|
176
|
+
buffer = Buffer.from(arrayBuf);
|
|
177
|
+
|
|
178
|
+
// Save to cache
|
|
179
|
+
if (cacheDir) {
|
|
180
|
+
writeFileSync(path.join(cacheDir, filename), buffer);
|
|
181
|
+
}
|
|
182
|
+
} catch (err) {
|
|
183
|
+
console.warn(
|
|
184
|
+
`⚠️ [ForgeWP Font Orchestrator] Failed to download font ${rule.remoteUrl}: ${err.message}`,
|
|
185
|
+
);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
writeFileSync(outputPath, buffer);
|
|
191
|
+
|
|
192
|
+
enriched.push({
|
|
193
|
+
...rule,
|
|
194
|
+
filename,
|
|
195
|
+
localPath: outputPath,
|
|
196
|
+
publicUrl: `assets/fonts/${filename}`,
|
|
197
|
+
});
|
|
198
|
+
index++;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
return enriched;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Generate a local `@font-face` CSS stylesheet.
|
|
206
|
+
*
|
|
207
|
+
* @param {Array<Object>} enrichedRules
|
|
208
|
+
* @param {string} [fontUrlPrefix='./'] - Relative URL prefix for font references in CSS
|
|
209
|
+
* @returns {string}
|
|
210
|
+
*/
|
|
211
|
+
export function generateLocalFontFaceCss(enrichedRules, fontUrlPrefix = './') {
|
|
212
|
+
const cssBlocks = enrichedRules.map((rule) => {
|
|
213
|
+
const url = `${fontUrlPrefix}${rule.filename}`;
|
|
214
|
+
const rangeLine = rule.unicodeRange
|
|
215
|
+
? `\n unicode-range: ${rule.unicodeRange};`
|
|
216
|
+
: '';
|
|
217
|
+
|
|
218
|
+
return `@font-face {
|
|
219
|
+
font-family: '${rule.family}';
|
|
220
|
+
font-style: ${rule.style};
|
|
221
|
+
font-weight: ${rule.weight};
|
|
222
|
+
font-display: ${rule.display};
|
|
223
|
+
src: url('${url}') format('${rule.format}');${rangeLine}
|
|
224
|
+
}`;
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
return cssBlocks.join('\n\n') + '\n';
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* High-level Font Orchestration runner.
|
|
232
|
+
*
|
|
233
|
+
* @param {string} themeRoot
|
|
234
|
+
* @param {Object} config
|
|
235
|
+
* @param {import('./asset-graph.js').AssetGraph} assetGraph
|
|
236
|
+
* @param {Object} [options]
|
|
237
|
+
* @returns {Promise<{ strategy: string, downloadedCount: number, fontsCssPath: string|null, preloadFonts: string[] }>}
|
|
238
|
+
*/
|
|
239
|
+
export async function orchestrateFonts(
|
|
240
|
+
themeRoot,
|
|
241
|
+
config,
|
|
242
|
+
assetGraph,
|
|
243
|
+
options = {},
|
|
244
|
+
) {
|
|
245
|
+
const outDir = options.outDir || path.join(themeRoot, '.forgewp', 'out');
|
|
246
|
+
const targetFontsDir = path.join(outDir, 'assets', 'fonts');
|
|
247
|
+
const cacheDir = path.join(themeRoot, '.forgewp', 'cache', 'fonts');
|
|
248
|
+
|
|
249
|
+
// Discover font configuration
|
|
250
|
+
const fontConfig =
|
|
251
|
+
config.fonts?.google || config.settings?.typography?.googleFonts || null;
|
|
252
|
+
const families = normalizeFontFamilies(fontConfig);
|
|
253
|
+
const strategy = (
|
|
254
|
+
config.fonts?.google?.strategy ||
|
|
255
|
+
config.settings?.typography?.fontStrategy ||
|
|
256
|
+
'self-host'
|
|
257
|
+
).toLowerCase();
|
|
258
|
+
const display = config.fonts?.google?.display || 'swap';
|
|
259
|
+
|
|
260
|
+
if (families.length === 0 || strategy === 'remote') {
|
|
261
|
+
return {
|
|
262
|
+
strategy: families.length > 0 ? 'remote' : 'none',
|
|
263
|
+
downloadedCount: 0,
|
|
264
|
+
fontsCssPath: null,
|
|
265
|
+
preloadFonts: [],
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Scan codebase for used font weights BEFORE downloading
|
|
270
|
+
const { usedWeights } = scanFontWeightUsage(themeRoot);
|
|
271
|
+
const unusedWeights = detectUnusedConfiguredWeights(fontConfig, usedWeights);
|
|
272
|
+
|
|
273
|
+
if (unusedWeights.length > 0) {
|
|
274
|
+
for (const u of unusedWeights) {
|
|
275
|
+
if (process.env.FORGEWP_VERBOSE === '1')
|
|
276
|
+
console.warn(
|
|
277
|
+
`⚠️ [ForgeWP Fonts] Unused Font Weight: ${u.family} ${u.weight} (${u.reason}). Removing it from wp.config.ts saves ~${u.sizeKb} KB.`,
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
try {
|
|
283
|
+
const rawCss = await fetchGoogleFontCss(families, display);
|
|
284
|
+
const parsedRules = parseFontFaceRules(rawCss);
|
|
285
|
+
const enrichedRules = await downloadFontFiles(
|
|
286
|
+
parsedRules,
|
|
287
|
+
targetFontsDir,
|
|
288
|
+
cacheDir,
|
|
289
|
+
);
|
|
290
|
+
|
|
291
|
+
if (enrichedRules.length === 0) {
|
|
292
|
+
return {
|
|
293
|
+
strategy: 'self-host',
|
|
294
|
+
downloadedCount: 0,
|
|
295
|
+
fontsCssPath: null,
|
|
296
|
+
preloadFonts: [],
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const localCss = generateLocalFontFaceCss(enrichedRules, './');
|
|
301
|
+
const fontsCssPath = path.join(targetFontsDir, 'fonts.css');
|
|
302
|
+
writeFileSync(fontsCssPath, localCss, 'utf8');
|
|
303
|
+
|
|
304
|
+
// Register critical font weights (e.g. 400 and 700) in assetGraph for high-priority preload
|
|
305
|
+
const preloadFonts = [];
|
|
306
|
+
if (assetGraph) {
|
|
307
|
+
const primaryWeights = ['400', '500', '600', '700'];
|
|
308
|
+
const seenFamilies = new Set();
|
|
309
|
+
|
|
310
|
+
for (const rule of enrichedRules) {
|
|
311
|
+
if (
|
|
312
|
+
primaryWeights.includes(String(rule.weight)) &&
|
|
313
|
+
!seenFamilies.has(`${rule.family}-${rule.weight}`)
|
|
314
|
+
) {
|
|
315
|
+
seenFamilies.add(`${rule.family}-${rule.weight}`);
|
|
316
|
+
preloadFonts.push(rule.publicUrl);
|
|
317
|
+
|
|
318
|
+
assetGraph.addAsset({
|
|
319
|
+
id: rule.publicUrl,
|
|
320
|
+
type: 'font',
|
|
321
|
+
classification: 'local-static',
|
|
322
|
+
source: rule.publicUrl,
|
|
323
|
+
priority: true,
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
return {
|
|
330
|
+
strategy: 'self-host',
|
|
331
|
+
downloadedCount: enrichedRules.length,
|
|
332
|
+
fontsCssPath,
|
|
333
|
+
preloadFonts,
|
|
334
|
+
enrichedRules,
|
|
335
|
+
};
|
|
336
|
+
} catch (err) {
|
|
337
|
+
console.warn(
|
|
338
|
+
`⚠️ [ForgeWP Font Orchestrator] Self-hosting failed: ${err.message}. Falling back to remote enqueuing.`,
|
|
339
|
+
);
|
|
340
|
+
return {
|
|
341
|
+
strategy: 'remote-fallback',
|
|
342
|
+
downloadedCount: 0,
|
|
343
|
+
fontsCssPath: null,
|
|
344
|
+
preloadFonts: [],
|
|
345
|
+
enrichedRules: [],
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Tailwind font weight class to numeric weight mapping.
|
|
6
|
+
*/
|
|
7
|
+
const TAILWIND_WEIGHT_MAP = {
|
|
8
|
+
'font-thin': 100,
|
|
9
|
+
'font-extralight': 200,
|
|
10
|
+
'font-light': 300,
|
|
11
|
+
'font-normal': 400,
|
|
12
|
+
'font-medium': 500,
|
|
13
|
+
'font-semibold': 600,
|
|
14
|
+
'font-bold': 700,
|
|
15
|
+
'font-extrabold': 800,
|
|
16
|
+
'font-black': 900,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Scan theme codebase for used font weights (Tailwind classes, inline styles, CSS).
|
|
21
|
+
*
|
|
22
|
+
* @param {string} themeRoot
|
|
23
|
+
* @returns {{ usedWeights: Set<number>, occurrences: Map<number, number> }}
|
|
24
|
+
*/
|
|
25
|
+
export function scanFontWeightUsage(themeRoot) {
|
|
26
|
+
const usedWeights = new Set([400]); // 400 is always assumed as base normal text
|
|
27
|
+
const occurrences = new Map();
|
|
28
|
+
|
|
29
|
+
const srcDir = path.join(themeRoot, 'src');
|
|
30
|
+
if (!existsSync(srcDir)) {
|
|
31
|
+
return { usedWeights, occurrences };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const files = [];
|
|
35
|
+
function scanDir(dir) {
|
|
36
|
+
try {
|
|
37
|
+
const entries = readdirSync(dir, { withFileTypes: true });
|
|
38
|
+
for (const entry of entries) {
|
|
39
|
+
const full = path.join(dir, entry.name);
|
|
40
|
+
if (entry.isDirectory()) {
|
|
41
|
+
if (entry.name !== 'node_modules' && entry.name !== '.forgewp' && entry.name !== 'dist') {
|
|
42
|
+
scanDir(full);
|
|
43
|
+
}
|
|
44
|
+
} else if (entry.isFile() && /\.(tsx|jsx|ts|js|css|html)$/i.test(entry.name)) {
|
|
45
|
+
files.push(full);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
} catch {}
|
|
49
|
+
}
|
|
50
|
+
scanDir(srcDir);
|
|
51
|
+
|
|
52
|
+
// Also check globals.css or main css files in root
|
|
53
|
+
const globalCss = path.join(themeRoot, 'src', 'app', 'globals.css');
|
|
54
|
+
if (existsSync(globalCss) && !files.includes(globalCss)) {
|
|
55
|
+
files.push(globalCss);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
for (const file of files) {
|
|
59
|
+
let content = '';
|
|
60
|
+
try {
|
|
61
|
+
content = readFileSync(file, 'utf8');
|
|
62
|
+
} catch {
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 1. Scan standard Tailwind font weight utility classes
|
|
67
|
+
for (const [cls, weight] of Object.entries(TAILWIND_WEIGHT_MAP)) {
|
|
68
|
+
const regex = new RegExp(`\\b${cls}\\b`, 'g');
|
|
69
|
+
const matches = content.match(regex);
|
|
70
|
+
if (matches) {
|
|
71
|
+
usedWeights.add(weight);
|
|
72
|
+
occurrences.set(weight, (occurrences.get(weight) || 0) + matches.length);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 2. Scan arbitrary Tailwind classes like font-[500] or font-[600]
|
|
77
|
+
const arbitraryRegex = /\bfont-\[(\d{3})\]/g;
|
|
78
|
+
let arbMatch;
|
|
79
|
+
while ((arbMatch = arbitraryRegex.exec(content)) !== null) {
|
|
80
|
+
const weight = Number(arbMatch[1]);
|
|
81
|
+
if (weight >= 100 && weight <= 900) {
|
|
82
|
+
usedWeights.add(weight);
|
|
83
|
+
occurrences.set(weight, (occurrences.get(weight) || 0) + 1);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 3. Scan CSS font-weight declarations (e.g. font-weight: 600 or fontWeight: 600)
|
|
88
|
+
const cssWeightRegex = /(?:font-weight|fontWeight)\s*[:=]\s*['"]?(\d{3}|bold|normal|light|thin|black)['"]?/gi;
|
|
89
|
+
let cssMatch;
|
|
90
|
+
while ((cssMatch = cssWeightRegex.exec(content)) !== null) {
|
|
91
|
+
const val = cssMatch[1].toLowerCase();
|
|
92
|
+
const weight =
|
|
93
|
+
val === 'bold'
|
|
94
|
+
? 700
|
|
95
|
+
: val === 'normal'
|
|
96
|
+
? 400
|
|
97
|
+
: val === 'light'
|
|
98
|
+
? 300
|
|
99
|
+
: val === 'thin'
|
|
100
|
+
? 100
|
|
101
|
+
: val === 'black'
|
|
102
|
+
? 900
|
|
103
|
+
: Number(val);
|
|
104
|
+
if (weight >= 100 && weight <= 900) {
|
|
105
|
+
usedWeights.add(weight);
|
|
106
|
+
occurrences.set(weight, (occurrences.get(weight) || 0) + 1);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return { usedWeights, occurrences };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Extract structured family names and declared weights from config.
|
|
116
|
+
*
|
|
117
|
+
* @param {Array<string>|Object} configFonts
|
|
118
|
+
* @returns {Array<{ family: string, weights: number[] }>}
|
|
119
|
+
*/
|
|
120
|
+
export function extractConfiguredWeights(configFonts) {
|
|
121
|
+
if (!configFonts) return [];
|
|
122
|
+
const rawList = Array.isArray(configFonts)
|
|
123
|
+
? configFonts
|
|
124
|
+
: configFonts.families || [];
|
|
125
|
+
|
|
126
|
+
const results = [];
|
|
127
|
+
|
|
128
|
+
for (const item of rawList) {
|
|
129
|
+
if (typeof item !== 'string') continue;
|
|
130
|
+
const [name, rest] = item.split(':');
|
|
131
|
+
const family = name.replace(/\+/g, ' ').trim();
|
|
132
|
+
const weights = [];
|
|
133
|
+
|
|
134
|
+
if (rest) {
|
|
135
|
+
// Find all 3-digit weights in the string (e.g. wght@300;400;500 or 0,400;0,500)
|
|
136
|
+
const weightMatches = rest.match(/\b([1-9]00)\b/g);
|
|
137
|
+
if (weightMatches) {
|
|
138
|
+
for (const w of weightMatches) {
|
|
139
|
+
const num = Number(w);
|
|
140
|
+
if (!weights.includes(num)) {
|
|
141
|
+
weights.push(num);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} else {
|
|
146
|
+
weights.push(400);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
results.push({ family, weights });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return results;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Detect configured font weights that are declared in wp.config.ts but never used in the project source.
|
|
157
|
+
*
|
|
158
|
+
* @param {Array<string>|Object} configFonts
|
|
159
|
+
* @param {Set<number>} usedWeights
|
|
160
|
+
* @returns {Array<{ family: string, weight: number, sizeKb: number, reason: string }>}
|
|
161
|
+
*/
|
|
162
|
+
export function detectUnusedConfiguredWeights(configFonts, usedWeights) {
|
|
163
|
+
const configured = extractConfiguredWeights(configFonts);
|
|
164
|
+
const unused = [];
|
|
165
|
+
|
|
166
|
+
for (const entry of configured) {
|
|
167
|
+
for (const weight of entry.weights) {
|
|
168
|
+
// 400 is considered default base text
|
|
169
|
+
if (weight === 400) continue;
|
|
170
|
+
|
|
171
|
+
if (!usedWeights.has(weight)) {
|
|
172
|
+
unused.push({
|
|
173
|
+
family: entry.family,
|
|
174
|
+
weight,
|
|
175
|
+
sizeKb: 22.5, // Average WOFF2 font slice size
|
|
176
|
+
reason: `Declared in wp.config.ts but no 'font-${getTailwindName(weight)}' or font-weight ${weight} found in src/`,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return unused;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function getTailwindName(weight) {
|
|
186
|
+
switch (weight) {
|
|
187
|
+
case 100: return 'thin';
|
|
188
|
+
case 200: return 'extralight';
|
|
189
|
+
case 300: return 'light';
|
|
190
|
+
case 500: return 'medium';
|
|
191
|
+
case 600: return 'semibold';
|
|
192
|
+
case 700: return 'bold';
|
|
193
|
+
case 800: return 'extrabold';
|
|
194
|
+
case 900: return 'black';
|
|
195
|
+
default: return String(weight);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Detect unused font weights from downloaded font rules.
|
|
201
|
+
*/
|
|
202
|
+
export function detectUnusedFontWeights(enrichedFontRules, usedWeights) {
|
|
203
|
+
if (!Array.isArray(enrichedFontRules) || enrichedFontRules.length === 0) {
|
|
204
|
+
return [];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const unused = [];
|
|
208
|
+
const seen = new Set();
|
|
209
|
+
|
|
210
|
+
for (const rule of enrichedFontRules) {
|
|
211
|
+
const numWeight = Number(rule.weight);
|
|
212
|
+
if (isNaN(numWeight)) continue;
|
|
213
|
+
|
|
214
|
+
if (numWeight === 400) continue;
|
|
215
|
+
|
|
216
|
+
if (!usedWeights.has(numWeight)) {
|
|
217
|
+
const key = `${rule.family}-${rule.weight}`;
|
|
218
|
+
if (!seen.has(key)) {
|
|
219
|
+
seen.add(key);
|
|
220
|
+
let sizeBytes = 0;
|
|
221
|
+
if (rule.localPath && existsSync(rule.localPath)) {
|
|
222
|
+
try {
|
|
223
|
+
sizeBytes = statSync(rule.localPath).size;
|
|
224
|
+
} catch {}
|
|
225
|
+
}
|
|
226
|
+
const sizeKb = sizeBytes > 0 ? Number((sizeBytes / 1024).toFixed(1)) : 22.5;
|
|
227
|
+
|
|
228
|
+
unused.push({
|
|
229
|
+
family: rule.family,
|
|
230
|
+
weight: numWeight,
|
|
231
|
+
style: rule.style,
|
|
232
|
+
filename: rule.filename,
|
|
233
|
+
localPath: rule.localPath,
|
|
234
|
+
sizeBytes,
|
|
235
|
+
sizeKb,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return unused;
|
|
242
|
+
}
|