@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.
Files changed (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -0,0 +1,432 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+
5
+ const require = createRequire(import.meta.url);
6
+ let ts;
7
+ try {
8
+ ts = require('typescript');
9
+ } catch {
10
+ // TypeScript is available in devDependencies
11
+ }
12
+
13
+ /**
14
+ * Classify the source origin of an asset reference.
15
+ *
16
+ * @param {string|number|object} src
17
+ * @param {number|string} [id]
18
+ * @param {string} [field]
19
+ * @returns {'wp-attachment' | 'local-static' | 'external-url'}
20
+ */
21
+ export function classifyAssetSource(src, id, field) {
22
+ if (id !== undefined && id !== null && String(id).trim().length > 0) {
23
+ return 'wp-attachment';
24
+ }
25
+ if (field !== undefined && field !== null && String(field).trim().length > 0) {
26
+ return 'wp-attachment';
27
+ }
28
+ if (typeof src === 'number') {
29
+ return 'wp-attachment';
30
+ }
31
+ if (src && typeof src === 'object') {
32
+ if ('id' in src || 'sizes' in src) return 'wp-attachment';
33
+ if ('src' in src) return classifyAssetSource(src.src);
34
+ }
35
+ if (typeof src === 'string') {
36
+ const trimmed = src.trim();
37
+ if (/^\d+$/.test(trimmed) || trimmed === 'featuredImage' || trimmed === 'featured_image') {
38
+ return 'wp-attachment';
39
+ }
40
+ if (/^https?:\/\//i.test(trimmed) || /^\/\//.test(trimmed)) {
41
+ return 'external-url';
42
+ }
43
+ return 'local-static';
44
+ }
45
+ return 'local-static';
46
+ }
47
+
48
+ /**
49
+ * Represents a single asset node in the ForgeWP Asset Graph.
50
+ */
51
+ export class AssetNode {
52
+ constructor(data) {
53
+ this.id = data.id;
54
+ this.type = data.type || 'image'; // 'image' | 'font' | 'svg' | 'css' | 'js' | 'external'
55
+ this.classification = data.classification || 'local-static'; // 'wp-attachment' | 'local-static' | 'external-url'
56
+ this.source = data.source || '';
57
+ this.resolvedPath = data.resolvedPath || null;
58
+ this.output = data.output || null;
59
+ this.width = data.width != null ? Number(data.width) || null : null;
60
+ this.height = data.height != null ? Number(data.height) || null : null;
61
+ this.priority = Boolean(data.priority);
62
+ this.loading = data.loading || (this.priority ? 'eager' : 'lazy');
63
+ this.decoding = data.decoding || 'async';
64
+ this.sizes = data.sizes || null;
65
+ this.placeholder = data.placeholder || 'empty';
66
+ this.blurDataURL = data.blurDataURL || null;
67
+ this.optimize = data.optimize || 'auto';
68
+ this.field = data.field || null;
69
+ this.attachmentId = data.attachmentId != null ? Number(data.attachmentId) || null : null;
70
+ this.variants = Array.isArray(data.variants) ? [...data.variants] : (data.variants || null);
71
+ this.srcset = data.srcset || null;
72
+ this.usageLocations = Array.isArray(data.usageLocations) ? [...data.usageLocations] : [];
73
+ }
74
+
75
+ addUsage(location) {
76
+ if (!location) return;
77
+ const exists = this.usageLocations.some(
78
+ (u) => u.file === location.file && u.line === location.line,
79
+ );
80
+ if (!exists) {
81
+ this.usageLocations.push(location);
82
+ }
83
+ }
84
+ }
85
+
86
+ /**
87
+ * AssetGraph manages and queries the dependency graph of all assets in a ForgeWP theme.
88
+ */
89
+ export class AssetGraph {
90
+ constructor(themeRoot = '') {
91
+ this.themeRoot = themeRoot;
92
+ this.nodes = new Map(); // asset ID -> AssetNode
93
+ }
94
+
95
+ /**
96
+ * Add or merge an asset node into the graph.
97
+ * @param {Object} data
98
+ * @returns {AssetNode}
99
+ */
100
+ addAsset(data) {
101
+ const id = data.id || data.source || `asset-${this.nodes.size + 1}`;
102
+ let node = this.nodes.get(id);
103
+
104
+ if (!node) {
105
+ node = new AssetNode({ ...data, id });
106
+ this.nodes.set(id, node);
107
+ } else {
108
+ // Merge properties
109
+ if (data.priority) node.priority = true;
110
+ if (data.loading === 'eager') node.loading = 'eager';
111
+ if (data.width && !node.width) node.width = Number(data.width) || null;
112
+ if (data.height && !node.height) node.height = Number(data.height) || null;
113
+ if (data.sizes && !node.sizes) node.sizes = data.sizes;
114
+ if (data.blurDataURL && !node.blurDataURL) node.blurDataURL = data.blurDataURL;
115
+ if (data.resolvedPath && !node.resolvedPath) node.resolvedPath = data.resolvedPath;
116
+ if (data.attachmentId && !node.attachmentId) node.attachmentId = Number(data.attachmentId) || null;
117
+ if (data.field && !node.field) node.field = data.field;
118
+ if (data.optimize && node.optimize === 'auto') node.optimize = data.optimize;
119
+ if (data.variants) node.variants = data.variants;
120
+ if (data.srcset) node.srcset = data.srcset;
121
+ }
122
+
123
+ if (data.usageLocations) {
124
+ for (const loc of data.usageLocations) {
125
+ node.addUsage(loc);
126
+ }
127
+ }
128
+
129
+ return node;
130
+ }
131
+
132
+ getAsset(id) {
133
+ return this.nodes.get(id) || null;
134
+ }
135
+
136
+ getAllAssets() {
137
+ return Array.from(this.nodes.values());
138
+ }
139
+
140
+ getLocalImages() {
141
+ return this.getAllAssets().filter(
142
+ (a) => a.classification === 'local-static' && (a.type === 'image' || a.type === 'svg'),
143
+ );
144
+ }
145
+
146
+ getPriorityAssets() {
147
+ return this.getAllAssets().filter((a) => a.priority === true);
148
+ }
149
+
150
+ getExternalAssets() {
151
+ return this.getAllAssets().filter((a) => a.classification === 'external-url');
152
+ }
153
+
154
+ getWpAttachments() {
155
+ return this.getAllAssets().filter((a) => a.classification === 'wp-attachment');
156
+ }
157
+
158
+ toJSON() {
159
+ const assets = {};
160
+ for (const [id, node] of this.nodes) {
161
+ assets[id] = {
162
+ id: node.id,
163
+ type: node.type,
164
+ classification: node.classification,
165
+ source: node.source,
166
+ output: node.output,
167
+ width: node.width,
168
+ height: node.height,
169
+ priority: node.priority,
170
+ loading: node.loading,
171
+ decoding: node.decoding,
172
+ sizes: node.sizes,
173
+ placeholder: node.placeholder,
174
+ optimize: node.optimize,
175
+ field: node.field,
176
+ attachmentId: node.attachmentId,
177
+ usageCount: node.usageLocations.length,
178
+ usageLocations: node.usageLocations,
179
+ };
180
+ }
181
+ return {
182
+ themeRoot: this.themeRoot,
183
+ totalAssets: this.nodes.size,
184
+ assets,
185
+ };
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Scan a theme codebase and populate an AssetGraph.
191
+ *
192
+ * @param {string} themeRoot
193
+ * @param {Object} [options]
194
+ * @returns {AssetGraph}
195
+ */
196
+ export function scanAssetGraph(themeRoot, options = {}) {
197
+ const graph = new AssetGraph(themeRoot);
198
+ const srcDir = path.join(themeRoot, 'src');
199
+
200
+ if (!existsSync(srcDir)) {
201
+ return graph;
202
+ }
203
+
204
+ const files = [];
205
+ function scanDir(dir) {
206
+ try {
207
+ const entries = readdirSync(dir, { withFileTypes: true });
208
+ for (const entry of entries) {
209
+ const full = path.join(dir, entry.name);
210
+ if (entry.isDirectory()) {
211
+ if (entry.name !== 'node_modules' && entry.name !== '.forgewp' && entry.name !== 'dist') {
212
+ scanDir(full);
213
+ }
214
+ } else if (entry.isFile() && /\.(tsx|jsx|ts|js|html)$/.test(entry.name)) {
215
+ files.push(full);
216
+ }
217
+ }
218
+ } catch {}
219
+ }
220
+ scanDir(srcDir);
221
+
222
+ for (const file of files) {
223
+ let content = '';
224
+ try {
225
+ content = readFileSync(file, 'utf8');
226
+ } catch {
227
+ continue;
228
+ }
229
+
230
+ const relFile = path.relative(themeRoot, file).replace(/\\/g, '/');
231
+
232
+ if (!ts) {
233
+ // Regex fallback if TS is unavailable
234
+ scanWithRegex(content, relFile, themeRoot, graph);
235
+ continue;
236
+ }
237
+
238
+ try {
239
+ const sourceFile = ts.createSourceFile(
240
+ file,
241
+ content,
242
+ ts.ScriptTarget.Latest,
243
+ true,
244
+ file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
245
+ );
246
+ scanAst(sourceFile, relFile, themeRoot, graph, ts);
247
+ } catch {
248
+ scanWithRegex(content, relFile, themeRoot, graph);
249
+ }
250
+ }
251
+
252
+ return graph;
253
+ }
254
+
255
+ /**
256
+ * AST Scanner for JSX elements (<WpImage>, <img>) and static imports.
257
+ */
258
+ function scanAst(sourceFile, relFile, themeRoot, graph, ts) {
259
+ function getAttrValue(attr) {
260
+ if (!attr || !attr.initializer) return true;
261
+ if (ts.isStringLiteral(attr.initializer)) return attr.initializer.text;
262
+ if (ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
263
+ const expr = attr.initializer.expression;
264
+ if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) return expr.text;
265
+ if (ts.isNumericLiteral(expr)) return Number(expr.text);
266
+ if (expr.kind === ts.SyntaxKind.TrueKeyword) return true;
267
+ if (expr.kind === ts.SyntaxKind.FalseKeyword) return false;
268
+ }
269
+ return null;
270
+ }
271
+
272
+ function getStaticFallbackSource(expr) {
273
+ if (
274
+ ts.isStringLiteral(expr) ||
275
+ ts.isNoSubstitutionTemplateLiteral(expr)
276
+ ) {
277
+ return expr.text;
278
+ }
279
+ if (
280
+ ts.isBinaryExpression(expr) &&
281
+ (expr.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
282
+ expr.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken)
283
+ ) {
284
+ return getStaticFallbackSource(expr.right);
285
+ }
286
+ return null;
287
+ }
288
+
289
+ function visit(node) {
290
+ // 1. Detect static image / font import declarations
291
+ if (
292
+ ts.isImportDeclaration(node) &&
293
+ node.moduleSpecifier &&
294
+ ts.isStringLiteral(node.moduleSpecifier)
295
+ ) {
296
+ const spec = node.moduleSpecifier.text;
297
+ if (/\.(png|jpe?g|webp|avif|svg|gif|woff2?|ttf|eot)$/i.test(spec)) {
298
+ const isFont = /\.(woff2?|ttf|eot)$/i.test(spec);
299
+ const isSvg = /\.svg$/i.test(spec);
300
+ const type = isFont ? 'font' : isSvg ? 'svg' : 'image';
301
+ const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;
302
+ graph.addAsset({
303
+ id: spec,
304
+ type,
305
+ classification: 'local-static',
306
+ source: spec,
307
+ usageLocations: [{ file: relFile, line }],
308
+ });
309
+ }
310
+ }
311
+
312
+ // 2. Detect JSX Elements (<WpImage ... /> or <img ... />)
313
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
314
+ const tagName = node.tagName.getText(sourceFile);
315
+
316
+ if (tagName === 'WpImage' || tagName === 'img') {
317
+ const attributes = {};
318
+ let srcIsFallback = false;
319
+ for (const prop of node.attributes.properties) {
320
+ if (ts.isJsxAttribute(prop) && prop.name) {
321
+ const attrName = prop.name.getText(sourceFile);
322
+ let value = getAttrValue(prop);
323
+ if (
324
+ attrName === 'src' &&
325
+ value == null &&
326
+ ts.isJsxExpression(prop.initializer) &&
327
+ prop.initializer.expression
328
+ ) {
329
+ value = getStaticFallbackSource(prop.initializer.expression);
330
+ srcIsFallback = value != null;
331
+ }
332
+ attributes[attrName] = value;
333
+ }
334
+ }
335
+
336
+ const src = attributes.src;
337
+ const id = attributes.id;
338
+ const field = attributes.field;
339
+ const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;
340
+
341
+ if (src || id !== undefined || field !== undefined) {
342
+ const classification = classifyAssetSource(src, id, field);
343
+ const rawSource = src != null ? String(src) : (field ? `field:${field}` : `id:${id}`);
344
+ const assetId = String(src || (field ? `field:${field}` : `id:${id}`));
345
+ const isSvg = typeof src === 'string' && /\.svg(\?.*)?$/i.test(src);
346
+ const type = isSvg ? 'svg' : (classification === 'external-url' ? 'image' : 'image');
347
+
348
+ graph.addAsset({
349
+ id: assetId,
350
+ type,
351
+ classification,
352
+ source: rawSource,
353
+ width: attributes.width,
354
+ height: attributes.height,
355
+ priority:
356
+ !srcIsFallback &&
357
+ (attributes.priority === true ||
358
+ attributes.fetchpriority === 'high' ||
359
+ attributes.fetchPriority === 'high'),
360
+ loading: attributes.loading,
361
+ decoding: attributes.decoding || 'async',
362
+ sizes: attributes.sizes,
363
+ placeholder: attributes.placeholder,
364
+ blurDataURL: attributes.blurDataURL,
365
+ optimize: attributes.optimize,
366
+ field: typeof field === 'string' ? field : undefined,
367
+ attachmentId: id != null && !isNaN(Number(id)) ? Number(id) : undefined,
368
+ usageLocations: [{ file: relFile, line, component: tagName }],
369
+ });
370
+ }
371
+ }
372
+ }
373
+
374
+ ts.forEachChild(node, visit);
375
+ }
376
+
377
+ visit(sourceFile);
378
+ }
379
+
380
+ /**
381
+ * Fallback regex scanner if TypeScript parser is unavailable.
382
+ */
383
+ function scanWithRegex(content, relFile, themeRoot, graph) {
384
+ // Static imports
385
+ const importRegex = /import\s+[\w*\s{},]+\s+from\s+['"]([^'"]+\.(?:png|jpe?g|webp|avif|svg|gif|woff2?|ttf|eot))['"]/gi;
386
+ let match;
387
+ while ((match = importRegex.exec(content)) !== null) {
388
+ const spec = match[1];
389
+ const isFont = /\.(woff2?|ttf|eot)$/i.test(spec);
390
+ const isSvg = /\.svg$/i.test(spec);
391
+ graph.addAsset({
392
+ id: spec,
393
+ type: isFont ? 'font' : isSvg ? 'svg' : 'image',
394
+ classification: 'local-static',
395
+ source: spec,
396
+ usageLocations: [{ file: relFile }],
397
+ });
398
+ }
399
+
400
+ // <WpImage> and <img> tags
401
+ const tagRegex = /<(?:WpImage|img)\b([^>]*)\/?>/gi;
402
+ while ((match = tagRegex.exec(content)) !== null) {
403
+ const attrsStr = match[1];
404
+ const getAttr = (name) => {
405
+ const m = attrsStr.match(new RegExp(`\\b${name}=(?:["']([^"']*)["']|{([^}]*)})`, 'i'));
406
+ return m ? m[1] || m[2] : null;
407
+ };
408
+
409
+ const src = getAttr('src');
410
+ const id = getAttr('id');
411
+ const field = getAttr('field');
412
+ const priority = attrsStr.includes('priority') || attrsStr.includes('fetchpriority="high"');
413
+
414
+ if (src || id || field) {
415
+ const classification = classifyAssetSource(src, id, field);
416
+ const rawSource = src || (field ? `field:${field}` : `id:${id}`);
417
+ graph.addAsset({
418
+ id: rawSource,
419
+ type: typeof src === 'string' && /\.svg/i.test(src) ? 'svg' : 'image',
420
+ classification,
421
+ source: rawSource,
422
+ width: getAttr('width'),
423
+ height: getAttr('height'),
424
+ priority,
425
+ sizes: getAttr('sizes'),
426
+ field: field || undefined,
427
+ attachmentId: id && !isNaN(Number(id)) ? Number(id) : undefined,
428
+ usageLocations: [{ file: relFile }],
429
+ });
430
+ }
431
+ }
432
+ }
@@ -0,0 +1,125 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { optimizeImageFile } from './image-optimizer.js';
4
+ import { processExternalBuildOptimizations } from './external-fetcher.js';
5
+
6
+ /**
7
+ * Supported raster image file extensions for Sharp optimization.
8
+ */
9
+ export const RASTER_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.tiff', '.gif'];
10
+
11
+ /**
12
+ * Resolve the absolute on-disk path for a local static asset reference.
13
+ *
14
+ * @param {string} themeRoot
15
+ * @param {string} sourcePath
16
+ * @returns {string|null}
17
+ */
18
+ export function resolveLocalAssetPath(themeRoot, sourcePath) {
19
+ if (!sourcePath || typeof sourcePath !== 'string') return null;
20
+
21
+ // Clean relative prefixes
22
+ const clean = sourcePath.replace(/^(\/|\.\/|@\/)+/, '');
23
+
24
+ const candidatePaths = [
25
+ path.join(themeRoot, clean),
26
+ path.join(themeRoot, 'public', clean),
27
+ path.join(themeRoot, 'src', clean),
28
+ path.join(themeRoot, 'src', 'assets', clean),
29
+ path.join(themeRoot, 'src', 'assets', 'images', clean),
30
+ path.join(themeRoot, 'assets', clean),
31
+ ];
32
+
33
+ for (const candidate of candidatePaths) {
34
+ if (existsSync(candidate) && statSync(candidate).isFile()) {
35
+ return candidate;
36
+ }
37
+ }
38
+
39
+ return null;
40
+ }
41
+
42
+ /**
43
+ * Execute the build-time asset pipeline over an AssetGraph.
44
+ *
45
+ * @param {string} themeRoot - Theme root directory
46
+ * @param {import('./asset-graph.js').AssetGraph} assetGraph
47
+ * @param {Object} [options]
48
+ * @param {string} [options.outDir] - Target output directory (e.g. .forgewp/out/theme)
49
+ * @param {string} [options.cacheDir] - Cache directory (e.g. .forgewp/cache/images)
50
+ * @param {number} [options.quality=80] - WebP quality
51
+ * @returns {Promise<{ processedCount: number, cachedCount: number, totalVariants: number, errors: Array }>}
52
+ */
53
+ export async function runAssetPipeline(themeRoot, assetGraph, options = {}) {
54
+ const outDir = options.outDir || path.join(themeRoot, '.forgewp', 'out');
55
+ const targetImagesDir = path.join(outDir, 'assets', 'images');
56
+ const cacheDir = options.cacheDir || path.join(themeRoot, '.forgewp', 'cache', 'images');
57
+ const quality = options.quality || 80;
58
+
59
+ const localImages = assetGraph ? assetGraph.getLocalImages() : [];
60
+ const results = {
61
+ processedCount: 0,
62
+ cachedCount: 0,
63
+ totalVariants: 0,
64
+ errors: [],
65
+ };
66
+
67
+ for (const node of localImages) {
68
+ const ext = path.extname(node.source).toLowerCase();
69
+ if (!RASTER_EXTENSIONS.includes(ext)) {
70
+ continue; // Skip SVGs or unsupported formats for raster transcoding
71
+ }
72
+
73
+ const resolvedPath = node.resolvedPath || resolveLocalAssetPath(themeRoot, node.source);
74
+ if (!resolvedPath) {
75
+ continue;
76
+ }
77
+
78
+ node.resolvedPath = resolvedPath;
79
+
80
+ try {
81
+ const optimized = await optimizeImageFile(resolvedPath, {
82
+ outputDir: targetImagesDir,
83
+ cacheDir,
84
+ quality,
85
+ publicUrlPrefix: 'assets/images',
86
+ });
87
+
88
+ // Update AssetNode with intrinsic dimensions and generated variants
89
+ if (!node.width && optimized.original.width) {
90
+ node.width = optimized.original.width;
91
+ }
92
+ if (!node.height && optimized.original.height) {
93
+ node.height = optimized.original.height;
94
+ }
95
+ node.sizes = node.sizes || '(max-width: 1024px) 100vw, 50vw';
96
+ node.srcset = optimized.srcset;
97
+ node.blurDataURL = optimized.blurDataURL;
98
+ node.variants = optimized.variants;
99
+
100
+ results.processedCount++;
101
+ if (optimized.cached) results.cachedCount++;
102
+ results.totalVariants += (optimized.variants || []).length;
103
+ } catch (err) {
104
+ results.errors.push({
105
+ assetId: node.id,
106
+ source: node.source,
107
+ message: err.message,
108
+ });
109
+ }
110
+ }
111
+
112
+ // Process external images with optimize="build"
113
+ try {
114
+ const extResults = await processExternalBuildOptimizations(themeRoot, assetGraph, options);
115
+ results.processedCount += extResults.processedCount;
116
+ results.errors.push(...extResults.errors);
117
+ } catch (err) {
118
+ results.errors.push({
119
+ assetId: 'external-optimizations',
120
+ message: err.message,
121
+ });
122
+ }
123
+
124
+ return results;
125
+ }