@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,229 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import crypto from 'node:crypto';
|
|
4
|
+
import sharp from 'sharp';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Standard responsive breakpoints for static image generation.
|
|
8
|
+
*/
|
|
9
|
+
export const DEFAULT_RESPONSIVE_WIDTHS = [480, 768, 1024, 1440, 1920];
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Extract intrinsic image metadata (dimensions, format, alpha).
|
|
13
|
+
*
|
|
14
|
+
* @param {string|Buffer} input - File path or buffer
|
|
15
|
+
* @returns {Promise<{ width: number, height: number, format: string, aspectRatio: number, hasAlpha: boolean }>}
|
|
16
|
+
*/
|
|
17
|
+
export async function getImageMetadata(input) {
|
|
18
|
+
const meta = await sharp(input).metadata();
|
|
19
|
+
const width = meta.width || 0;
|
|
20
|
+
const height = meta.height || 0;
|
|
21
|
+
const aspectRatio = width && height ? Number((width / height).toFixed(4)) : 1;
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
width,
|
|
25
|
+
height,
|
|
26
|
+
format: meta.format || 'unknown',
|
|
27
|
+
aspectRatio,
|
|
28
|
+
hasAlpha: Boolean(meta.hasAlpha),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Generate a lightweight, base64-encoded WebP blur placeholder (LQIP).
|
|
34
|
+
*
|
|
35
|
+
* @param {string|Buffer} input - File path or buffer
|
|
36
|
+
* @param {number} [size=16] - Dimension of the placeholder thumbnail in pixels
|
|
37
|
+
* @returns {Promise<string>} Data URL string (e.g. "data:image/webp;base64,...")
|
|
38
|
+
*/
|
|
39
|
+
export async function generateBlurPlaceholder(input, size = 16) {
|
|
40
|
+
try {
|
|
41
|
+
const buffer = await sharp(input)
|
|
42
|
+
.resize(size, size, { fit: 'inside' })
|
|
43
|
+
.webp({ quality: 20, effort: 3 })
|
|
44
|
+
.toBuffer();
|
|
45
|
+
|
|
46
|
+
return `data:image/webp;base64,${buffer.toString('base64')}`;
|
|
47
|
+
} catch {
|
|
48
|
+
return '';
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Compute a deterministic SHA256 hash from file buffer and options.
|
|
54
|
+
*/
|
|
55
|
+
export function computeImageHash(buffer, options = {}) {
|
|
56
|
+
return crypto
|
|
57
|
+
.createHash('sha256')
|
|
58
|
+
.update(buffer)
|
|
59
|
+
.update(JSON.stringify(options))
|
|
60
|
+
.digest('hex')
|
|
61
|
+
.slice(0, 16);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Persistent build cache for optimized image variants and metadata.
|
|
66
|
+
*/
|
|
67
|
+
export class ImageOptimizationCache {
|
|
68
|
+
constructor(cacheDir) {
|
|
69
|
+
this.cacheDir = cacheDir;
|
|
70
|
+
this.manifestPath = path.join(cacheDir, 'manifest.json');
|
|
71
|
+
this.entries = new Map();
|
|
72
|
+
this.load();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
load() {
|
|
76
|
+
if (existsSync(this.manifestPath)) {
|
|
77
|
+
try {
|
|
78
|
+
const raw = readFileSync(this.manifestPath, 'utf8');
|
|
79
|
+
const data = JSON.parse(raw);
|
|
80
|
+
for (const [key, val] of Object.entries(data)) {
|
|
81
|
+
this.entries.set(key, val);
|
|
82
|
+
}
|
|
83
|
+
} catch {}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
save() {
|
|
88
|
+
try {
|
|
89
|
+
if (!existsSync(this.cacheDir)) {
|
|
90
|
+
mkdirSync(this.cacheDir, { recursive: true });
|
|
91
|
+
}
|
|
92
|
+
const data = Object.fromEntries(this.entries.entries());
|
|
93
|
+
writeFileSync(this.manifestPath, JSON.stringify(data, null, 2), 'utf8');
|
|
94
|
+
} catch {}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
get(hash) {
|
|
98
|
+
return this.entries.get(hash) || null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
set(hash, result) {
|
|
102
|
+
this.entries.set(hash, result);
|
|
103
|
+
this.save();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Generate optimized WebP responsive variants from a source image buffer.
|
|
109
|
+
*
|
|
110
|
+
* @param {Buffer} inputBuffer - Raw image buffer
|
|
111
|
+
* @param {string} baseName - Base name without extension (e.g. "hero-banner")
|
|
112
|
+
* @param {string} outputDir - Directory to write variants to
|
|
113
|
+
* @param {Object} [options]
|
|
114
|
+
* @param {number[]} [options.widths] - Target responsive widths
|
|
115
|
+
* @param {number} [options.quality=80] - Compression quality
|
|
116
|
+
* @param {string} [options.publicUrlPrefix='assets/images'] - Prefix for srcset URL references
|
|
117
|
+
* @returns {Promise<{ original: Object, variants: Array, srcset: string, blurDataURL: string }>}
|
|
118
|
+
*/
|
|
119
|
+
export async function generateResponsiveVariants(
|
|
120
|
+
inputBuffer,
|
|
121
|
+
baseName,
|
|
122
|
+
outputDir,
|
|
123
|
+
options = {},
|
|
124
|
+
) {
|
|
125
|
+
const metadata = await getImageMetadata(inputBuffer);
|
|
126
|
+
const origWidth = metadata.width;
|
|
127
|
+
const origHeight = metadata.height;
|
|
128
|
+
const quality = options.quality || 80;
|
|
129
|
+
const targetWidths = options.widths || DEFAULT_RESPONSIVE_WIDTHS;
|
|
130
|
+
const publicPrefix = (options.publicUrlPrefix || 'assets/images').replace(/\/+$/, '');
|
|
131
|
+
|
|
132
|
+
// Filter widths: never upscale beyond original intrinsic resolution
|
|
133
|
+
let widthsToGenerate = targetWidths.filter((w) => w <= origWidth);
|
|
134
|
+
if (widthsToGenerate.length === 0 && origWidth > 0) {
|
|
135
|
+
widthsToGenerate = [origWidth];
|
|
136
|
+
} else if (!widthsToGenerate.includes(origWidth) && origWidth > 0) {
|
|
137
|
+
widthsToGenerate.push(origWidth);
|
|
138
|
+
}
|
|
139
|
+
widthsToGenerate.sort((a, b) => a - b);
|
|
140
|
+
|
|
141
|
+
if (!existsSync(outputDir)) {
|
|
142
|
+
mkdirSync(outputDir, { recursive: true });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const variants = [];
|
|
146
|
+
const srcsetParts = [];
|
|
147
|
+
|
|
148
|
+
for (const width of widthsToGenerate) {
|
|
149
|
+
const filename = `${baseName}-${width}w.webp`;
|
|
150
|
+
const outputPath = path.join(outputDir, filename);
|
|
151
|
+
const calculatedHeight = origWidth && origHeight
|
|
152
|
+
? Math.round((width / origWidth) * origHeight)
|
|
153
|
+
: undefined;
|
|
154
|
+
|
|
155
|
+
// Resize and compress to WebP
|
|
156
|
+
await sharp(inputBuffer)
|
|
157
|
+
.resize(width, calculatedHeight, { fit: 'inside', withoutEnlargement: true })
|
|
158
|
+
.webp({ quality, effort: 4 })
|
|
159
|
+
.toFile(outputPath);
|
|
160
|
+
|
|
161
|
+
const publicUrl = `${publicPrefix}/${filename}`;
|
|
162
|
+
|
|
163
|
+
variants.push({
|
|
164
|
+
width,
|
|
165
|
+
height: calculatedHeight,
|
|
166
|
+
format: 'webp',
|
|
167
|
+
filename,
|
|
168
|
+
path: outputPath,
|
|
169
|
+
publicUrl,
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
srcsetParts.push(`${publicUrl} ${width}w`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const blurDataURL = await generateBlurPlaceholder(inputBuffer);
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
original: metadata,
|
|
179
|
+
variants,
|
|
180
|
+
srcset: srcsetParts.join(', '),
|
|
181
|
+
blurDataURL,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* High-level optimizer function for a single image file on disk.
|
|
187
|
+
*
|
|
188
|
+
* @param {string} inputPath - Absolute file path to the source image
|
|
189
|
+
* @param {Object} [options]
|
|
190
|
+
* @param {string} [options.outputDir] - Destination directory for variants
|
|
191
|
+
* @param {string} [options.cacheDir] - Directory for image cache
|
|
192
|
+
* @param {number[]} [options.widths] - Target widths
|
|
193
|
+
* @param {number} [options.quality=80] - Compression quality
|
|
194
|
+
* @param {string} [options.publicUrlPrefix='assets/images']
|
|
195
|
+
* @returns {Promise<{ original: Object, variants: Array, srcset: string, blurDataURL: string, cached: boolean }>}
|
|
196
|
+
*/
|
|
197
|
+
export async function optimizeImageFile(inputPath, options = {}) {
|
|
198
|
+
if (!existsSync(inputPath)) {
|
|
199
|
+
throw new Error(`[ForgeWP Optimizer] Source image not found: ${inputPath}`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const inputBuffer = readFileSync(inputPath);
|
|
203
|
+
const parsed = path.parse(inputPath);
|
|
204
|
+
const baseName = parsed.name.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
|
|
205
|
+
const outputDir = options.outputDir || path.join(path.dirname(inputPath), 'optimized');
|
|
206
|
+
const cache = options.cacheDir ? new ImageOptimizationCache(options.cacheDir) : null;
|
|
207
|
+
|
|
208
|
+
const hash = computeImageHash(inputBuffer, {
|
|
209
|
+
widths: options.widths,
|
|
210
|
+
quality: options.quality,
|
|
211
|
+
publicUrlPrefix: options.publicUrlPrefix,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
if (cache) {
|
|
215
|
+
const cached = cache.get(hash);
|
|
216
|
+
if (cached && cached.variants && cached.variants.every((v) => existsSync(v.path))) {
|
|
217
|
+
return { ...cached, cached: true };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const result = await generateResponsiveVariants(inputBuffer, baseName, outputDir, options);
|
|
222
|
+
const payload = { ...result, hash };
|
|
223
|
+
|
|
224
|
+
if (cache) {
|
|
225
|
+
cache.set(hash, payload);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return { ...payload, cached: false };
|
|
229
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export {
|
|
2
|
+
AssetGraph,
|
|
3
|
+
AssetNode,
|
|
4
|
+
scanAssetGraph,
|
|
5
|
+
classifyAssetSource,
|
|
6
|
+
} from './asset-graph.js';
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
DEFAULT_RESPONSIVE_WIDTHS,
|
|
10
|
+
getImageMetadata,
|
|
11
|
+
generateBlurPlaceholder,
|
|
12
|
+
computeImageHash,
|
|
13
|
+
generateResponsiveVariants,
|
|
14
|
+
optimizeImageFile,
|
|
15
|
+
ImageOptimizationCache,
|
|
16
|
+
} from './image-optimizer.js';
|
|
17
|
+
|
|
18
|
+
export {
|
|
19
|
+
RASTER_EXTENSIONS,
|
|
20
|
+
resolveLocalAssetPath,
|
|
21
|
+
runAssetPipeline,
|
|
22
|
+
} from './asset-pipeline.js';
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
generatePreloadTags,
|
|
26
|
+
} from './preload-generator.js';
|
|
27
|
+
|
|
28
|
+
export {
|
|
29
|
+
computeUrlHash,
|
|
30
|
+
fetchExternalImage,
|
|
31
|
+
processExternalBuildOptimizations,
|
|
32
|
+
} from './external-fetcher.js';
|
|
33
|
+
|
|
34
|
+
export {
|
|
35
|
+
normalizeFontFamilies,
|
|
36
|
+
fetchGoogleFontCss,
|
|
37
|
+
parseFontFaceRules,
|
|
38
|
+
downloadFontFiles,
|
|
39
|
+
generateLocalFontFaceCss,
|
|
40
|
+
orchestrateFonts,
|
|
41
|
+
} from './font-orchestrator.js';
|
|
42
|
+
|
|
43
|
+
export {
|
|
44
|
+
scanFontWeightUsage,
|
|
45
|
+
detectUnusedFontWeights,
|
|
46
|
+
} from './font-usage-scanner.js';
|
|
47
|
+
|
|
48
|
+
export {
|
|
49
|
+
generateAssetManifest,
|
|
50
|
+
printAssetDiagnosticsReport,
|
|
51
|
+
} from './diagnostics-report.js';
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate <link rel="preload"> tags for high-priority / LCP assets.
|
|
3
|
+
*
|
|
4
|
+
* @param {import('./asset-graph.js').AssetGraph} assetGraph
|
|
5
|
+
* @param {Object} [options]
|
|
6
|
+
* @param {boolean} [options.isPhp=true] - True if generating PHP get_theme_file_uri() tags
|
|
7
|
+
* @returns {string[]} Array of HTML/PHP <link rel="preload"> tag strings
|
|
8
|
+
*/
|
|
9
|
+
export function generatePreloadTags(assetGraph, options = {}) {
|
|
10
|
+
if (!assetGraph) return [];
|
|
11
|
+
|
|
12
|
+
const isPhp = options.isPhp !== false;
|
|
13
|
+
const priorityAssets = assetGraph.getPriorityAssets();
|
|
14
|
+
const preloadTags = [];
|
|
15
|
+
|
|
16
|
+
for (const node of priorityAssets) {
|
|
17
|
+
if (node.type === 'image') {
|
|
18
|
+
if (node.classification === 'external-url') {
|
|
19
|
+
preloadTags.push(
|
|
20
|
+
`<link rel="preload" as="image" href="${node.source}" fetchpriority="high">`,
|
|
21
|
+
);
|
|
22
|
+
} else if (node.classification === 'local-static') {
|
|
23
|
+
const cleanPath = node.source.replace(/^(\/|\.\/|@\/)+/, '');
|
|
24
|
+
|
|
25
|
+
if (node.variants && node.variants.length > 0) {
|
|
26
|
+
// Choose largest or default variant for fallback href
|
|
27
|
+
const primaryVariant = node.variants[node.variants.length - 1];
|
|
28
|
+
const primaryRel = primaryVariant.publicUrl;
|
|
29
|
+
const hrefExpr = isPhp
|
|
30
|
+
? `<?php echo esc_url( get_theme_file_uri( '${primaryRel}' ) ); ?>`
|
|
31
|
+
: primaryRel;
|
|
32
|
+
|
|
33
|
+
// Build imagesrcset with get_theme_file_uri if in PHP mode
|
|
34
|
+
let imagesrcsetExpr = node.srcset;
|
|
35
|
+
if (isPhp && node.variants.length > 0) {
|
|
36
|
+
const phpSrcsetParts = node.variants.map((v) => {
|
|
37
|
+
return `<?php echo esc_url( get_theme_file_uri( '${v.publicUrl}' ) ); ?> ${v.width}w`;
|
|
38
|
+
});
|
|
39
|
+
imagesrcsetExpr = phpSrcsetParts.join(', ');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const sizesAttr = node.sizes ? ` imagesizes="${node.sizes}"` : '';
|
|
43
|
+
|
|
44
|
+
preloadTags.push(
|
|
45
|
+
`<link rel="preload" as="image" href="${hrefExpr}" fetchpriority="high" imagesrcset="${imagesrcsetExpr}"${sizesAttr}>`,
|
|
46
|
+
);
|
|
47
|
+
} else {
|
|
48
|
+
const hrefExpr = isPhp
|
|
49
|
+
? `<?php echo esc_url( get_theme_file_uri( '${cleanPath}' ) ); ?>`
|
|
50
|
+
: cleanPath;
|
|
51
|
+
|
|
52
|
+
preloadTags.push(
|
|
53
|
+
`<link rel="preload" as="image" href="${hrefExpr}" fetchpriority="high">`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
} else if (node.type === 'font') {
|
|
58
|
+
const cleanPath = node.source.replace(/^(\/|\.\/|@\/)+/, '');
|
|
59
|
+
const hrefExpr = isPhp
|
|
60
|
+
? `<?php echo esc_url( get_theme_file_uri( '${cleanPath}' ) ); ?>`
|
|
61
|
+
: cleanPath;
|
|
62
|
+
|
|
63
|
+
preloadTags.push(
|
|
64
|
+
`<link rel="preload" as="font" type="font/woff2" crossorigin href="${hrefExpr}">`,
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return preloadTags;
|
|
70
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Root-relative public files (`public/logo.png` → `/logo.png`) work in Vite
|
|
3
|
+
* and break after hydration on WordPress: the client bundle still points at
|
|
4
|
+
* the site root, while the file lives in the theme. Rewrite those string
|
|
5
|
+
* literals to the theme URI the hydrator already publishes.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
const MEDIA_EXT = /\.(png|jpe?g|webp|gif|svg|avif|mp4|webm|ogg|mp3|wav|woff2?|ttf|eot)$/i;
|
|
11
|
+
|
|
12
|
+
export const PUBLIC_ASSET_RUNTIME =
|
|
13
|
+
'(window.forgeWpHydration&&window.forgeWpHydration.themeUri||"")';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {string} themeRoot
|
|
17
|
+
* @returns {string[]} URL paths, longest first (`/assets/logo.png`)
|
|
18
|
+
*/
|
|
19
|
+
export function collectPublicAssetUrls(themeRoot) {
|
|
20
|
+
const publicDir = path.join(themeRoot, 'public');
|
|
21
|
+
if (!existsSync(publicDir)) return [];
|
|
22
|
+
const urls = [];
|
|
23
|
+
|
|
24
|
+
function walk(dir) {
|
|
25
|
+
let items;
|
|
26
|
+
try {
|
|
27
|
+
items = readdirSync(dir, { withFileTypes: true });
|
|
28
|
+
} catch {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
for (const item of items) {
|
|
32
|
+
const full = path.join(dir, item.name);
|
|
33
|
+
if (item.isDirectory()) {
|
|
34
|
+
walk(full);
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (!item.isFile() || !MEDIA_EXT.test(item.name)) continue;
|
|
38
|
+
const rel = path.relative(publicDir, full).split(path.sep).join('/');
|
|
39
|
+
urls.push(`/${rel}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
walk(publicDir);
|
|
44
|
+
urls.sort((a, b) => b.length - a.length);
|
|
45
|
+
return urls;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function escapeRegExp(value) {
|
|
49
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Replace a quoted public URL with a theme-uri expression.
|
|
54
|
+
* `String.replace` does not rescan the inserted text, so the quoted path
|
|
55
|
+
* inside the expression is not rewritten again.
|
|
56
|
+
*
|
|
57
|
+
* @param {string} source
|
|
58
|
+
* @param {string[]} urls
|
|
59
|
+
* @returns {string}
|
|
60
|
+
*/
|
|
61
|
+
export function rewriteJsPublicAssetUrls(source, urls) {
|
|
62
|
+
if (!source || !urls?.length) return source || '';
|
|
63
|
+
let out = source;
|
|
64
|
+
for (const url of urls) {
|
|
65
|
+
const re = new RegExp(`(['"\`])${escapeRegExp(url)}\\1`, 'g');
|
|
66
|
+
const literal = JSON.stringify(url);
|
|
67
|
+
out = out.replace(re, `${PUBLIC_ASSET_RUNTIME}+${literal}`);
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* CSS cannot read `window`. Files in `assets/` reference a public
|
|
74
|
+
* `/assets/...` file as a sibling, and a public root file as `../file`.
|
|
75
|
+
*
|
|
76
|
+
* @param {string} urlPath
|
|
77
|
+
* @returns {string}
|
|
78
|
+
*/
|
|
79
|
+
export function cssUrlForPublicAsset(urlPath) {
|
|
80
|
+
if (urlPath.startsWith('/assets/')) return urlPath.slice('/assets/'.length);
|
|
81
|
+
return `..${urlPath}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {string} source
|
|
86
|
+
* @param {string[]} urls
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
export function rewriteCssPublicAssetUrls(source, urls) {
|
|
90
|
+
if (!source || !urls?.length) return source || '';
|
|
91
|
+
let out = source;
|
|
92
|
+
for (const url of urls) {
|
|
93
|
+
const rel = cssUrlForPublicAsset(url);
|
|
94
|
+
const escaped = escapeRegExp(url);
|
|
95
|
+
out = out.replace(
|
|
96
|
+
new RegExp(`url\\(\\s*(['"])${escaped}\\1\\s*\\)`, 'g'),
|
|
97
|
+
`url("${rel}")`,
|
|
98
|
+
);
|
|
99
|
+
out = out.replace(
|
|
100
|
+
new RegExp(`url\\(\\s*${escaped}\\s*\\)`, 'g'),
|
|
101
|
+
`url("${rel}")`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {string} themeRoot
|
|
109
|
+
* @param {string} assetsDir theme `assets/` directory
|
|
110
|
+
* @returns {number} files changed
|
|
111
|
+
*/
|
|
112
|
+
export function rewriteThemePublicAssetUrls(themeRoot, assetsDir) {
|
|
113
|
+
const urls = collectPublicAssetUrls(themeRoot);
|
|
114
|
+
if (!urls.length || !existsSync(assetsDir)) return 0;
|
|
115
|
+
let changed = 0;
|
|
116
|
+
|
|
117
|
+
function walk(dir) {
|
|
118
|
+
let items;
|
|
119
|
+
try {
|
|
120
|
+
items = readdirSync(dir);
|
|
121
|
+
} catch {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
for (const name of items) {
|
|
125
|
+
const full = path.join(dir, name);
|
|
126
|
+
let st;
|
|
127
|
+
try {
|
|
128
|
+
st = statSync(full);
|
|
129
|
+
} catch {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (st.isDirectory()) {
|
|
133
|
+
walk(full);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (name.endsWith('.map')) continue;
|
|
137
|
+
const isJs = name.endsWith('.js') || name.endsWith('.mjs');
|
|
138
|
+
const isCss = name.endsWith('.css');
|
|
139
|
+
if (!isJs && !isCss) continue;
|
|
140
|
+
const before = readFileSync(full, 'utf8');
|
|
141
|
+
const after = isCss
|
|
142
|
+
? rewriteCssPublicAssetUrls(before, urls)
|
|
143
|
+
: rewriteJsPublicAssetUrls(before, urls);
|
|
144
|
+
if (after !== before) {
|
|
145
|
+
writeFileSync(full, after, 'utf8');
|
|
146
|
+
changed += 1;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
walk(assetsDir);
|
|
152
|
+
return changed;
|
|
153
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const blockAuthoringHelp = `
|
|
2
|
+
Choose an authoring path:
|
|
3
|
+
@forgewp-block Expose an existing component with inferred simple props.
|
|
4
|
+
defineBlock() Declare attributes, editor controls, and visitor rendering explicitly.
|
|
5
|
+
make:block Scaffold editable defineBlock source in src/blocks/.
|
|
6
|
+
make:shell Scaffold a layout parent with InnerBlocks; children remain separate blocks.
|
|
7
|
+
BlockArea Reserve Gutenberg content inside a fixed React template.
|
|
8
|
+
|
|
9
|
+
Generators write source files you can edit. Export generates WordPress block.json,
|
|
10
|
+
render.php, and editor assets from that source; keep changes in source files.
|
|
11
|
+
`;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared @babel/parser entry point for the block compiler's AST migration.
|
|
3
|
+
* One parse config, reused by every consumer that needs a real AST instead
|
|
4
|
+
* of scanning/re-scanning text — see forgewp_documentation_system_blueprint.md
|
|
5
|
+
* Phase 2 for the migration this backs.
|
|
6
|
+
*/
|
|
7
|
+
import { parse } from '@babel/parser';
|
|
8
|
+
import _traverse from '@babel/traverse';
|
|
9
|
+
|
|
10
|
+
export const traverse = _traverse.default || _traverse;
|
|
11
|
+
|
|
12
|
+
const PARSE_OPTIONS = {
|
|
13
|
+
sourceType: 'module',
|
|
14
|
+
plugins: ['jsx', 'typescript'],
|
|
15
|
+
allowReturnOutsideFunction: true,
|
|
16
|
+
allowAwaitOutsideFunction: true,
|
|
17
|
+
allowSuperOutsideMethod: true,
|
|
18
|
+
errorRecovery: false,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Parse a TSX/TS source snippet into a real AST.
|
|
23
|
+
*
|
|
24
|
+
* Many callers in this pipeline pass whole-file source, but plenty still pass
|
|
25
|
+
* text fragments produced by older text-scanning extraction (a JSX subtree,
|
|
26
|
+
* a function body's statements up to `return`, etc.) — some of those are not
|
|
27
|
+
* standalone-parseable. Callers that can tolerate a parse failure should
|
|
28
|
+
* catch; `tryParseSource` below is the non-throwing convenience for that.
|
|
29
|
+
*/
|
|
30
|
+
export function parseSource(code) {
|
|
31
|
+
return parse(code, PARSE_OPTIONS);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Same as parseSource, but returns null instead of throwing on malformed input. */
|
|
35
|
+
export function tryParseSource(code) {
|
|
36
|
+
try {
|
|
37
|
+
return parseSource(code);
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Phase 4 dead-fallback audit: env-gated counters on every legacy-fallback
|
|
45
|
+
* branch. Run any compile with FORGEWP_TRACE_FALLBACKS=1 and the per-site
|
|
46
|
+
* hit counts print to stderr on exit — a site that stays at zero across a
|
|
47
|
+
* full real-theme export is a candidate for deletion; a site with hits is
|
|
48
|
+
* load-bearing. Zero overhead when the env var is unset.
|
|
49
|
+
*/
|
|
50
|
+
const fallbackCounts = new Map();
|
|
51
|
+
|
|
52
|
+
export function markLegacyFallback(site) {
|
|
53
|
+
if (!process.env.FORGEWP_TRACE_FALLBACKS) return;
|
|
54
|
+
fallbackCounts.set(site, (fallbackCounts.get(site) || 0) + 1);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (process.env.FORGEWP_TRACE_FALLBACKS) {
|
|
58
|
+
process.on('exit', () => {
|
|
59
|
+
console.error('[fallback-trace] --- legacy fallback hits ---');
|
|
60
|
+
if (fallbackCounts.size === 0) {
|
|
61
|
+
console.error('[fallback-trace] (none — every code path stayed on the AST engine)');
|
|
62
|
+
}
|
|
63
|
+
for (const [site, n] of [...fallbackCounts].sort()) {
|
|
64
|
+
console.error(`[fallback-trace] ${site}: ${n}`);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|