@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
package/bin/export.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import path from "node:path";
4
- import { cwd } from "node:process";
5
- import pc from "picocolors";
6
- import { exportTheme } from "../lib/export-theme.js";
3
+ import path from 'node:path';
4
+ import { cwd } from 'node:process';
5
+ import pc from 'picocolors';
6
+ import { exportTheme } from '../lib/export-theme.js';
7
7
 
8
8
  function printHelp() {
9
9
  console.log(`
@@ -13,13 +13,15 @@ Options:
13
13
  --skip-build Use existing dist/ (skip Vite build)
14
14
  --no-zip Output folder only, no ZIP file
15
15
  --validate Run export validation checks after generation
16
- --strict Treat validation warnings as failures
16
+ --strict Fail on editable from/pick issues and (with --validate) validation warnings
17
17
  -h, --help Show help
18
18
 
19
19
  Examples:
20
20
  forgewp-export
21
21
  forgewp-export ./my-theme
22
22
  forgewp-export --skip-build
23
+ forgewp-export --strict
24
+ forgewp-export --validate --strict
23
25
  `);
24
26
  }
25
27
 
@@ -36,32 +38,32 @@ function parseArgs(argv) {
36
38
  for (let i = 0; i < argv.length; i += 1) {
37
39
  const arg = argv[i];
38
40
 
39
- if (arg === "-h" || arg === "--help") {
41
+ if (arg === '-h' || arg === '--help') {
40
42
  options.help = true;
41
43
  continue;
42
44
  }
43
45
 
44
- if (arg === "--skip-build") {
46
+ if (arg === '--skip-build') {
45
47
  options.skipBuild = true;
46
48
  continue;
47
49
  }
48
50
 
49
- if (arg === "--no-zip") {
51
+ if (arg === '--no-zip') {
50
52
  options.zip = false;
51
53
  continue;
52
54
  }
53
55
 
54
- if (arg === "--validate") {
56
+ if (arg === '--validate') {
55
57
  options.validate = true;
56
58
  continue;
57
59
  }
58
60
 
59
- if (arg === "--strict") {
61
+ if (arg === '--strict') {
60
62
  options.strict = true;
61
63
  continue;
62
64
  }
63
65
 
64
- if (arg.startsWith("-")) {
66
+ if (arg.startsWith('-')) {
65
67
  console.error(pc.red(`Unknown option: ${arg}`));
66
68
  process.exit(1);
67
69
  }
@@ -80,6 +82,42 @@ async function main() {
80
82
  return;
81
83
  }
82
84
 
85
+ const interactive = Boolean(process.stdout.isTTY);
86
+ const spinnerFrames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
87
+ let spinnerIndex = 0;
88
+ let spinnerTimer;
89
+ let activeStep = null;
90
+
91
+ const drawActiveStep = () => {
92
+ if (!activeStep || !interactive) return;
93
+ process.stdout.write(
94
+ `\r\x1b[2K ${pc.cyan(spinnerFrames[spinnerIndex])} ${activeStep.message}`,
95
+ );
96
+ spinnerIndex = (spinnerIndex + 1) % spinnerFrames.length;
97
+ };
98
+
99
+ const startStep = (evt) => {
100
+ if (activeStep) finishStep();
101
+ activeStep = evt;
102
+ spinnerIndex = 0;
103
+ if (interactive) {
104
+ drawActiveStep();
105
+ spinnerTimer = setInterval(drawActiveStep, 90);
106
+ } else {
107
+ console.log(` ${pc.cyan('⠋')} ${evt.message}`);
108
+ }
109
+ };
110
+
111
+ function finishStep(message = activeStep?.message) {
112
+ if (!activeStep) return;
113
+ if (spinnerTimer) clearInterval(spinnerTimer);
114
+ spinnerTimer = undefined;
115
+ if (interactive)
116
+ process.stdout.write(`\r\x1b[2K ${pc.green('✓')} ${message}\n`);
117
+ else console.log(` ${pc.green('✓')} ${message}`);
118
+ activeStep = null;
119
+ }
120
+
83
121
  try {
84
122
  const result = await exportTheme({
85
123
  themeRoot: options.themeRoot,
@@ -88,21 +126,32 @@ async function main() {
88
126
  validate: options.validate,
89
127
  strict: options.strict,
90
128
  onProgress: (evt) => {
91
- // Minimal CLI progress line (stage label)
92
- console.log(pc.dim(` [${evt.stage}] ${evt.message}`));
129
+ if (evt.stage === 'fonts-done') return;
130
+ if (evt.stage.endsWith('-done')) finishStep(evt.message);
131
+ else startStep(evt);
93
132
  },
94
133
  });
95
134
 
96
- console.log(pc.green("\n Export complete\n"));
97
- console.log(` ${pc.dim("Theme folder")} ${result.outDir}`);
98
- if (result.zipPath) {
99
- console.log(` ${pc.dim("ZIP")} ${result.zipPath}`);
100
- }
135
+ finishStep();
101
136
  console.log(
102
- `\n ${pc.dim("Install:")} Upload the ZIP to Appearance → Themes → Add New\n`,
137
+ pc.green(
138
+ ` ✓ Exported ${result.config.name} → ${result.zipPath || result.outDir}`,
139
+ ),
103
140
  );
104
141
  } catch (error) {
105
- console.error(pc.red(`\n Export failed: ${error instanceof Error ? error.message : error}\n`));
142
+ if (activeStep) {
143
+ if (spinnerTimer) clearInterval(spinnerTimer);
144
+ if (interactive)
145
+ process.stdout.write(
146
+ `\r\x1b[2K ${pc.red('✖')} ${activeStep.message}\n`,
147
+ );
148
+ activeStep = null;
149
+ }
150
+ console.error(
151
+ pc.red(
152
+ `\n Export failed: ${error instanceof Error ? error.message : error}\n`,
153
+ ),
154
+ );
106
155
  process.exit(1);
107
156
  }
108
157
  }
package/bin/fresh.js CHANGED
@@ -58,8 +58,13 @@ for (const targetPrune of directoriesToPrune) {
58
58
  }
59
59
 
60
60
  // 3. Restore Standard Database & Sitemap Menus from Core Blueprints
61
- const coreFilesToReset = ["cms/menus.json", "cms/mock-data.json"];
61
+ const coreFilesToReset = ["cms/menus.json", "cms/mock-data.json", "cms/products.json"];
62
62
  for (const relPath of coreFilesToReset) {
63
+ const tsVariant = relPath.replace(/\.json$/, ".ts");
64
+ if (existsSync(path.join(projectRoot, tsVariant))) {
65
+ console.log(` ${pc.gray("ℹ️ Skipping JSON reset")} ${pc.cyan(relPath)} ${pc.gray(`(${tsVariant} is the active source)`)}`);
66
+ continue;
67
+ }
63
68
  const fullPath = path.join(projectRoot, relPath);
64
69
  const blueprintContent = SYSTEM_BLUEPRINTS[relPath];
65
70
  if (blueprintContent) {
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import pc from 'picocolors';
6
6
  import { loadConfig } from '../lib/load-config.js';
7
7
  import { extractKeysFromDirectory } from '../lib/i18n/extractor.js';
8
+ import { loadTranslationsData, writeTranslationsData } from '../lib/functions/load-translations.js';
8
9
 
9
10
  console.log(`\n🗣️ ${pc.bold(pc.bgCyan(pc.black(" FORGEWP I18N EXTRACTOR ")))}\n`);
10
11
 
@@ -43,15 +44,7 @@ async function run() {
43
44
  fs.mkdirSync(cmsDir, { recursive: true });
44
45
  }
45
46
 
46
- const translationsPath = path.join(cmsDir, 'translations.json');
47
- let translations = {};
48
- if (fs.existsSync(translationsPath)) {
49
- try {
50
- translations = JSON.parse(fs.readFileSync(translationsPath, 'utf8'));
51
- } catch (err) {
52
- console.warn(pc.yellow(`⚠️ Could not parse existing translations.json, starting fresh.`));
53
- }
54
- }
47
+ let translations = loadTranslationsData(themeRoot);
55
48
 
56
49
  // Initialize missing locales
57
50
  for (const locale of locales) {
@@ -100,7 +93,7 @@ async function run() {
100
93
  sortedTranslations[locale] = sortedMap;
101
94
  }
102
95
 
103
- fs.writeFileSync(translationsPath, JSON.stringify(sortedTranslations, null, 2), 'utf8');
96
+ const translationsPath = writeTranslationsData(themeRoot, sortedTranslations);
104
97
 
105
98
  console.log(`\n${pc.bold("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")}`);
106
99
  console.log(` ✨ ${pc.green("Extraction completed successfully!")}`);
@@ -5,6 +5,8 @@ import path from 'node:path';
5
5
  import pc from 'picocolors';
6
6
  import { loadConfig } from '../lib/load-config.js';
7
7
  import { getProvider } from '../lib/i18n/providers.js';
8
+ import { createTranslationCache, translateMissingEntries } from '../lib/i18n/translation-cache.js';
9
+ import { loadTranslationsData, writeTranslationsData, translationsSourcePath } from '../lib/functions/load-translations.js';
8
10
 
9
11
  console.log(`\n🤖 ${pc.bold(pc.bgCyan(pc.black(" FORGEWP I18N AUTO-TRANSLATOR ")))}\n`);
10
12
 
@@ -30,22 +32,19 @@ async function run() {
30
32
  const locales = i18n.locales || ['en', 'de'];
31
33
  const providerName = i18n.provider || 'local';
32
34
 
33
- const translationsPath = path.join(themeRoot, 'cms', 'translations.json');
34
- if (!fs.existsSync(translationsPath)) {
35
- throw new Error(`Translations catalog not found at ${translationsPath}. Please run "pnpm forgewp i18n:extract" first.`);
35
+ const translationsPath = translationsSourcePath(themeRoot);
36
+ if (!translationsPath) {
37
+ throw new Error(`Translations catalog not found at cms/translations.ts or cms/translations.json. Please run "pnpm forgewp i18n:extract" first.`);
36
38
  }
37
39
 
38
- let translations = {};
39
- try {
40
- translations = JSON.parse(fs.readFileSync(translationsPath, 'utf8'));
41
- } catch (err) {
42
- throw new Error(`Failed to parse translations.json: ${err.message}`);
43
- }
40
+ const translations = loadTranslationsData(themeRoot);
44
41
 
45
42
  console.log(` 🔌 Active provider: ${pc.cyan(providerName)}`);
46
43
  console.log(` 🌐 Default locale: ${pc.yellow(defaultLocale)}`);
47
44
 
48
45
  const provider = getProvider(providerName, i18n.providerConfig || {});
46
+ const cache = providerName === 'local' || providerName === 'manual' ? null :
47
+ createTranslationCache(themeRoot, i18n.cache, providerName, i18n.providerConfig || {});
49
48
 
50
49
  let totalTranslated = 0;
51
50
 
@@ -74,32 +73,24 @@ async function run() {
74
73
  continue;
75
74
  }
76
75
 
77
- // Execute auto-translation
78
- const translatedMap = await provider.translate(untranslatedKeys, defaultLocale, locale);
79
-
80
- let successCount = 0;
81
- for (const key of untranslatedKeys) {
82
- if (translatedMap[key]) {
83
- localeMap[key] = translatedMap[key];
84
- successCount++;
85
- totalTranslated++;
86
- }
87
- }
76
+ const result = await translateMissingEntries(localeMap, defaultLocale, locale, provider, cache);
77
+ const successCount = result.translated + result.restored;
78
+ totalTranslated += result.translated;
79
+ if (result.restored) console.log(` Restored ${result.restored} translation(s) from cache.`);
88
80
  console.log(` ✅ Translated ${pc.green(successCount)}/${pc.yellow(untranslatedKeys.length)} keys successfully.`);
89
81
  }
90
82
 
91
- // Save changes
92
- fs.writeFileSync(translationsPath, JSON.stringify(translations, null, 2), 'utf8');
83
+ const writtenPath = writeTranslationsData(themeRoot, translations);
93
84
 
94
85
  console.log(`\n${pc.bold("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")}`);
95
86
  console.log(` ✨ ${pc.green("Translation execution completed successfully!")}`);
96
87
  if (totalTranslated > 0) {
97
88
  console.log(` 🎉 Total keys automated: ${pc.green(totalTranslated)}`);
98
89
  } else if (providerName === 'local' || providerName === 'manual') {
99
- console.log(` 💡 Setup complete. Open ${pc.cyan("cms/translations.json")} to write translations manually.`);
90
+ console.log(` 💡 Setup complete. Open ${pc.cyan(path.relative(themeRoot, writtenPath))} to write translations manually.`);
100
91
  console.log(` Or configure 'deepl' to auto-translate using environment variables.`);
101
92
  } else {
102
- console.log(` ✅ All locales are 100% up-to-date. No API calls were made.`);
93
+ console.log(` No new translations were returned. Review any remaining blank catalog entries.`);
103
94
  }
104
95
  console.log(`\n`);
105
96
 
package/bin/make-block.js CHANGED
@@ -2,11 +2,26 @@
2
2
 
3
3
  import { existsSync } from "node:fs";
4
4
  import path from "node:path";
5
+ import readline from "node:readline/promises";
6
+ import { stdin as input, stdout as output } from "node:process";
5
7
  import pc from "picocolors";
6
8
  import { loadConfig } from "../lib/load-config.js";
7
9
  import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
10
+ import { blockAuthoringHelp } from "../lib/block-authoring-help.js";
8
11
 
9
12
  const args = process.argv.slice(2);
13
+ if (args.includes('--help') || args.includes('-h')) {
14
+ console.log(`forgewp make:block <Name> [--attributes=title,description]
15
+
16
+ Creates editable React block source at src/blocks/<Name>.tsx.
17
+ --name <Name> Alternative to the positional name.
18
+ --attributes, --attrs Comma-separated string attribute names (default: title,description).
19
+ -h, --help Show help without creating files or prompting.
20
+
21
+ Example: pnpm forgewp make:block PromoCard --attributes=title,description
22
+ ${blockAuthoringHelp}`);
23
+ process.exit(0);
24
+ }
10
25
  let rawBlockName = args.find(a => !a.startsWith("-"));
11
26
 
12
27
  // Support --name TestimonialBlock or --name=TestimonialBlock
@@ -20,6 +35,15 @@ if (nameIndex !== -1 && args[nameIndex + 1]) {
20
35
  }
21
36
  }
22
37
 
38
+ if (!rawBlockName) {
39
+ const rl = readline.createInterface({ input, output });
40
+ try {
41
+ const answer = await rl.question(pc.cyan("? Enter a block name: "));
42
+ rawBlockName = answer.trim();
43
+ } catch (err) {}
44
+ rl.close();
45
+ }
46
+
23
47
  if (!rawBlockName) {
24
48
  console.error(pc.red("\n❌ Error: Please specify a block name."));
25
49
  console.log(pc.cyan(" Example: pnpm forgewp make:block TestimonialBlock"));
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import readline from "node:readline/promises";
6
+ import { stdin as input, stdout as output } from "node:process";
7
+ import pc from "picocolors";
8
+
9
+ const args = process.argv.slice(2);
10
+ let rawName = args.find(a => !a.startsWith("-"));
11
+
12
+ // Support --name AboutPage or --name=AboutPage
13
+ const nameIndex = args.indexOf("--name");
14
+ if (nameIndex !== -1 && args[nameIndex + 1]) {
15
+ rawName = args[nameIndex + 1];
16
+ } else {
17
+ const nameEqual = args.find(a => a.startsWith("--name="));
18
+ if (nameEqual) {
19
+ rawName = nameEqual.split("=")[1];
20
+ }
21
+ }
22
+
23
+ if (!rawName) {
24
+ const rl = readline.createInterface({ input, output });
25
+ try {
26
+ const answer = await rl.question(pc.cyan("? Enter a schema name (e.g. AboutPage or about-page): "));
27
+ rawName = answer.trim();
28
+ } catch (err) {}
29
+ rl.close();
30
+ }
31
+
32
+ if (!rawName) {
33
+ console.error(pc.red("\n❌ Error: Please specify a schema name."));
34
+ console.log(pc.cyan(" Example: pnpm forgewp make:editable AboutPage"));
35
+ console.log(pc.cyan(" Or: pnpm forgewp make:editable --name AboutPage\n"));
36
+ process.exit(1);
37
+ }
38
+
39
+ // kebab-case slug, matching the cms/editables/<slug>.ts convention
40
+ // (front-page.ts, hotels-page.ts, …)
41
+ const slug = rawName
42
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
43
+ .replace(/[\s_]+/g, "-")
44
+ .toLowerCase()
45
+ .replace(/[^a-z0-9-]/g, "");
46
+
47
+ if (!slug) {
48
+ console.error(pc.red("\n❌ Error: Invalid schema name. Use letters, numbers, dashes, and underscores.\n"));
49
+ process.exit(1);
50
+ }
51
+
52
+ const readableTitle = slug
53
+ .split("-")
54
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))
55
+ .join(" ");
56
+
57
+ const projectRoot = process.cwd();
58
+
59
+ if (!existsSync(path.join(projectRoot, "src"))) {
60
+ console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
61
+ process.exit(1);
62
+ }
63
+
64
+ // Parse --fields=name:type,name2:type2 (type defaults to "text" when omitted)
65
+ const VALID_TYPES = ["text", "richText", "image", "boolean", "repeater", "color", "url", "select", "number", "icon"];
66
+ let fieldsList = [];
67
+ const fieldsArg = args.find(a => /^-+fields=/.test(a));
68
+ if (fieldsArg) {
69
+ const raw = fieldsArg.split("=")[1] || "";
70
+ fieldsList = raw.split(",").map(f => f.trim()).filter(Boolean).map(f => {
71
+ const [fieldName, fieldType] = f.split(":").map(s => s.trim());
72
+ const type = VALID_TYPES.includes(fieldType) ? fieldType : "text";
73
+ return { name: fieldName, type };
74
+ });
75
+ } else {
76
+ const fieldsIndex = args.findIndex(a => a === "--fields");
77
+ if (fieldsIndex !== -1 && args[fieldsIndex + 1]) {
78
+ fieldsList = args[fieldsIndex + 1].split(",").map(f => f.trim()).filter(Boolean).map(f => {
79
+ const [fieldName, fieldType] = f.split(":").map(s => s.trim());
80
+ const type = VALID_TYPES.includes(fieldType) ? fieldType : "text";
81
+ return { name: fieldName, type };
82
+ });
83
+ }
84
+ }
85
+
86
+ if (fieldsList.length === 0) {
87
+ fieldsList = [
88
+ { name: "hero_title", type: "text" },
89
+ { name: "hero_subtitle", type: "text" },
90
+ ];
91
+ }
92
+
93
+ const editablesDir = path.join(projectRoot, "cms", "editables");
94
+ if (!existsSync(editablesDir)) {
95
+ mkdirSync(editablesDir, { recursive: true });
96
+ }
97
+
98
+ const targetFile = path.join(editablesDir, `${slug}.ts`);
99
+ if (existsSync(targetFile)) {
100
+ console.error(pc.red(`\n❌ Error: Schema "${slug}.ts" already exists at cms/editables/\n`));
101
+ process.exit(1);
102
+ }
103
+
104
+ const toLabel = (name) =>
105
+ name
106
+ .replace(/[_-]+/g, " ")
107
+ .split(" ")
108
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))
109
+ .join(" ");
110
+
111
+ const usedTypes = Array.from(new Set(fieldsList.map(f => f.type))).sort();
112
+ const importList = ["defineEditable", "getEditableDefaults", ...usedTypes].join(",\n ");
113
+
114
+ const fieldsPhp = fieldsList
115
+ .map(({ name, type }) => {
116
+ const label = toLabel(name);
117
+ if (type === "image") {
118
+ return ` ${name}: image({
119
+ label: '${label}',
120
+ default: '',
121
+ }),`;
122
+ }
123
+ if (type === "boolean") {
124
+ return ` ${name}: boolean({
125
+ label: '${label}',
126
+ default: false,
127
+ }),`;
128
+ }
129
+ return ` ${name}: ${type}({
130
+ label: '${label}',
131
+ default: 'Edit me',
132
+ }),`;
133
+ })
134
+ .join("\n");
135
+
136
+ const schemaTemplate = `/**
137
+ * ${readableTitle} — single editable contract.
138
+ *
139
+ * Source of truth for:
140
+ * - ACF field group (page-${slug}.php)
141
+ * - useWpMeta defaults on this template's section components
142
+ *
143
+ * Read a field with useWpMeta('key', defaults.key), or share a subset with
144
+ * a Gutenberg block via pickEditable(editable, { localName: 'key' }).
145
+ *
146
+ * Available field helpers: text, richText, image, boolean, repeater,
147
+ * color, url, select, number, icon — import the ones you use above.
148
+ */
149
+ import {
150
+ ${importList},
151
+ } from '@forgewp/react';
152
+
153
+ export const editable = defineEditable({
154
+ ${fieldsPhp}
155
+ });
156
+
157
+ export const defaults = getEditableDefaults(editable);
158
+ `;
159
+
160
+ writeFileSync(targetFile, schemaTemplate, "utf8");
161
+
162
+ console.log(pc.green(`\n⚡ Editable schema "${slug}" successfully created!`));
163
+ console.log(` File: ${pc.cyan(`cms/editables/${slug}.ts`)}`);
164
+ console.log(`\n🎉 Use it in a page or section component:`);
165
+ console.log(` ${pc.yellow(`import { editable, defaults } from '../../cms/editables/${slug}';`)}`);
166
+ console.log(` ${pc.yellow(`const ${fieldsList[0].name} = useWpMeta('${fieldsList[0].name}', defaults.${fieldsList[0].name});`)}\n`);
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import readline from "node:readline/promises";
6
+ import { stdin as input, stdout as output } from "node:process";
7
+ import pc from "picocolors";
8
+ import { loadConfig } from "../lib/load-config.js";
9
+ import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
10
+
11
+ const args = process.argv.slice(2);
12
+ let rawName = args.find(a => !a.startsWith("-"));
13
+
14
+ // Support --name Contact or --name=Contact
15
+ const nameIndex = args.indexOf("--name");
16
+ if (nameIndex !== -1 && args[nameIndex + 1]) {
17
+ rawName = args[nameIndex + 1];
18
+ } else {
19
+ const nameEqual = args.find(a => a.startsWith("--name="));
20
+ if (nameEqual) {
21
+ rawName = nameEqual.split("=")[1];
22
+ }
23
+ }
24
+
25
+ if (!rawName) {
26
+ const rl = readline.createInterface({ input, output });
27
+ try {
28
+ const answer = await rl.question(pc.cyan("? Enter a form name (e.g. Contact or contact): "));
29
+ rawName = answer.trim();
30
+ } catch (err) {}
31
+ rl.close();
32
+ }
33
+
34
+ if (!rawName) {
35
+ console.error(pc.red("\n❌ Error: Please specify a form name."));
36
+ console.log(pc.cyan(" Example: pnpm forgewp make:form Contact"));
37
+ console.log(pc.cyan(" Or: pnpm forgewp make:form --name Contact\n"));
38
+ process.exit(1);
39
+ }
40
+
41
+ // kebab-case slug, matching the cms/forms/<slug>.ts convention
42
+ // (mirrors cms/editables/<slug>.ts's filename-as-key convention)
43
+ const slug = rawName
44
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
45
+ .replace(/[\s_]+/g, "-")
46
+ .toLowerCase()
47
+ .replace(/[^a-z0-9-]/g, "");
48
+
49
+ if (!slug) {
50
+ console.error(pc.red("\n❌ Error: Invalid form name. Use letters, numbers, dashes, and underscores.\n"));
51
+ process.exit(1);
52
+ }
53
+
54
+ const pascalCase = slug
55
+ .split("-")
56
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1))
57
+ .join("");
58
+
59
+ const projectRoot = process.cwd();
60
+
61
+ if (!existsSync(path.join(projectRoot, "src"))) {
62
+ console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
63
+ process.exit(1);
64
+ }
65
+
66
+ if (existsSync(path.join(projectRoot, "cms", "forms", `${slug}.ts`))) {
67
+ console.error(pc.red(`\n❌ Error: Form "${slug}.ts" already exists at cms/forms/\n`));
68
+ process.exit(1);
69
+ }
70
+
71
+ // Parse --fields=name:type,name2:type2 (type defaults to "text" when omitted)
72
+ const VALID_TYPES = ["text", "email", "tel", "number", "textarea", "select", "checkbox"];
73
+ let fieldsList = [];
74
+ const fieldsArg = args.find(a => /^-+fields=/.test(a));
75
+ const fieldsRaw = fieldsArg
76
+ ? fieldsArg.split("=")[1] || ""
77
+ : (() => {
78
+ const i = args.findIndex(a => a === "--fields");
79
+ return i !== -1 && args[i + 1] ? args[i + 1] : "";
80
+ })();
81
+
82
+ if (fieldsRaw) {
83
+ fieldsList = fieldsRaw.split(",").map(f => f.trim()).filter(Boolean).map(f => {
84
+ const [fieldName, fieldType] = f.split(":").map(s => s.trim());
85
+ const type = VALID_TYPES.includes(fieldType) ? fieldType : "text";
86
+ return { name: fieldName, type };
87
+ });
88
+ } else {
89
+ fieldsList = [
90
+ { name: "name", type: "text" },
91
+ { name: "email", type: "email" },
92
+ { name: "message", type: "textarea" },
93
+ ];
94
+ }
95
+
96
+ // Parse --mailTo=admin (or a literal email / option:key — see WpFormConfig.mailTo)
97
+ let mailTo = "admin";
98
+ const mailToArg = args.find(a => a.startsWith("--mailTo="));
99
+ if (mailToArg) {
100
+ mailTo = mailToArg.split("=")[1] || "admin";
101
+ }
102
+
103
+ const projectRootForConfig = process.cwd();
104
+
105
+ let frameworkAdapter = "react";
106
+ try {
107
+ const config = await loadConfig(projectRootForConfig);
108
+ frameworkAdapter = config.frameworkAdapter || "react";
109
+ } catch (err) {
110
+ // Use default
111
+ }
112
+
113
+ try {
114
+ const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
115
+ const adapter = adapterModule.default || adapterModule;
116
+ if (typeof adapter.onMakeForm === "function") {
117
+ await adapter.onMakeForm(projectRoot, {
118
+ slug,
119
+ pascalCase,
120
+ fields: fieldsList,
121
+ mailTo,
122
+ pc,
123
+ });
124
+ } else {
125
+ console.error(pc.red(`\n❌ Error: Framework adapter "${frameworkAdapter}" does not support making forms.`));
126
+ process.exit(1);
127
+ }
128
+ } catch (err) {
129
+ console.error(pc.red(`\n❌ Failed to execute make:form: ${err.message}`));
130
+ process.exit(1);
131
+ }
@@ -2,6 +2,8 @@
2
2
 
3
3
  import { existsSync } from "node:fs";
4
4
  import path from "node:path";
5
+ import readline from "node:readline/promises";
6
+ import { stdin as input, stdout as output } from "node:process";
5
7
  import pc from "picocolors";
6
8
  import { loadConfig } from "../lib/load-config.js";
7
9
  import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
@@ -20,6 +22,15 @@ if (nameIndex !== -1 && args[nameIndex + 1]) {
20
22
  }
21
23
  }
22
24
 
25
+ if (!rawIslandName) {
26
+ const rl = readline.createInterface({ input, output });
27
+ try {
28
+ const answer = await rl.question(pc.cyan("? Enter an island name: "));
29
+ rawIslandName = answer.trim();
30
+ } catch (err) {}
31
+ rl.close();
32
+ }
33
+
23
34
  if (!rawIslandName) {
24
35
  console.error(pc.red("\n❌ Error: Please specify an island name."));
25
36
  console.log(pc.cyan(" Example: pnpm forgewp make:island CounterIsland"));