@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,221 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import pc from 'picocolors';
6
+
7
+ const args = process.argv.slice(2);
8
+
9
+ function getOption(name, fallback = '') {
10
+ const exactIndex = args.indexOf(`--${name}`);
11
+ if (exactIndex !== -1 && args[exactIndex + 1]) return args[exactIndex + 1];
12
+ const equal = args.find((arg) => arg.startsWith(`--${name}=`));
13
+ return equal ? equal.slice(name.length + 3) : fallback;
14
+ }
15
+
16
+ function toKebabCase(value) {
17
+ return value
18
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
19
+ .replace(/[\s_]+/g, '-')
20
+ .toLowerCase()
21
+ .replace(/[^a-z0-9-]/g, '')
22
+ .replace(/-+/g, '-')
23
+ .replace(/^-|-$/g, '');
24
+ }
25
+
26
+ function toPascalCase(value) {
27
+ return value
28
+ .split(/[-_\s]+/)
29
+ .filter(Boolean)
30
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
31
+ .join('');
32
+ }
33
+
34
+ function toSnakeCase(value) {
35
+ return value
36
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
37
+ .replace(/[\s-]+/g, '_')
38
+ .toLowerCase();
39
+ }
40
+
41
+ function parseFields() {
42
+ const raw = getOption('fields');
43
+ if (!raw) {
44
+ return [
45
+ { name: 'title', type: 'text' },
46
+ { name: 'description', type: 'richText' },
47
+ ];
48
+ }
49
+
50
+ const validTypes = new Set([
51
+ 'text',
52
+ 'richText',
53
+ 'image',
54
+ 'boolean',
55
+ 'repeater',
56
+ 'color',
57
+ 'url',
58
+ 'select',
59
+ 'number',
60
+ 'icon',
61
+ ]);
62
+
63
+ return raw
64
+ .split(',')
65
+ .map((entry) => entry.trim())
66
+ .filter(Boolean)
67
+ .map((entry) => {
68
+ const [name, requestedType = 'text'] = entry
69
+ .split(':')
70
+ .map((part) => part.trim());
71
+ return {
72
+ name,
73
+ type: validTypes.has(requestedType) ? requestedType : 'text',
74
+ };
75
+ })
76
+ .filter((field) => /^[a-zA-Z_$][\w$]*$/.test(field.name));
77
+ }
78
+
79
+ const rawName = getOption('name') || args.find((arg) => !arg.startsWith('-'));
80
+ if (!rawName) {
81
+ console.error(pc.red('\n❌ Error: Please specify a section name.'));
82
+ console.log(
83
+ pc.cyan(
84
+ ' Example: pnpm forgewp make:section HeroSection --page=front-page --block\n',
85
+ ),
86
+ );
87
+ process.exit(1);
88
+ }
89
+
90
+ const projectRoot = process.cwd();
91
+ if (!existsSync(path.join(projectRoot, 'src'))) {
92
+ console.error(
93
+ pc.red('\n❌ Error: "src" folder not found. Are you in your theme root?\n'),
94
+ );
95
+ process.exit(1);
96
+ }
97
+
98
+ const componentName = toPascalCase(rawName);
99
+ const slug =
100
+ toKebabCase(componentName.replace(/Section$/, '')) ||
101
+ toKebabCase(componentName);
102
+ const pageSlug = toKebabCase(getOption('page', 'front-page'));
103
+ const fields = parseFields();
104
+ const withBlock = args.includes('--block') || args.includes('--block=true');
105
+
106
+ if (fields.length === 0) {
107
+ console.error(pc.red('\n❌ Error: No valid fields were provided.\n'));
108
+ process.exit(1);
109
+ }
110
+
111
+ const schemaDir = path.join(projectRoot, 'cms', 'editables', 'sections');
112
+ const componentDir = path.join(projectRoot, 'src', 'components');
113
+ const schemaFile = path.join(schemaDir, `${slug}.ts`);
114
+ const pageFile = path.join(projectRoot, 'cms', 'editables', `${pageSlug}.ts`);
115
+ const componentFile = path.join(componentDir, `${componentName}.tsx`);
116
+ const pageExists = existsSync(pageFile);
117
+
118
+ for (const target of [schemaFile, componentFile]) {
119
+ if (existsSync(target)) {
120
+ console.error(
121
+ pc.red(
122
+ `\n❌ Error: File already exists: ${path.relative(projectRoot, target)}\n`,
123
+ ),
124
+ );
125
+ process.exit(1);
126
+ }
127
+ }
128
+
129
+ mkdirSync(schemaDir, { recursive: true });
130
+ mkdirSync(componentDir, { recursive: true });
131
+
132
+ const imports = Array.from(
133
+ new Set([
134
+ 'defineEditable',
135
+ 'getEditableDefaults',
136
+ ...fields.map((field) => field.type),
137
+ ]),
138
+ ).join(',\n ');
139
+ const fieldDefinitions = fields
140
+ .map(({ name, type }) => {
141
+ const defaultValue =
142
+ type === 'boolean'
143
+ ? 'false'
144
+ : type === 'number'
145
+ ? '0'
146
+ : type === 'image'
147
+ ? "''"
148
+ : type === 'repeater'
149
+ ? '[]'
150
+ : "'Edit me'";
151
+ return ` ${name}: ${type}({\n label: '${name.replace(/[_-]+/g, ' ')}',\n default: ${defaultValue},\n }),`;
152
+ })
153
+ .join('\n');
154
+
155
+ const pageFields = fields
156
+ .map(({ name }) => ` ${name}: '${slug}_${toSnakeCase(name)}',`)
157
+ .join('\n');
158
+ const renameFields = fields
159
+ .map(({ name }) => ` ${name}: '${toSnakeCase(name)}',`)
160
+ .join('\n');
161
+
162
+ const pageSchemaSource = `/**\n * ${pageSlug} — page editable contract composed from sections.\n */\nimport { buildPageEditable, getEditableDefaults } from '@forgewp/react';\nimport { editable as ${slug}Editable } from './sections/${slug}';\n\nexport const pageEditableSections = [\n {\n section: '${slug}',\n prefix: '${slug}_',\n rename: {\n${renameFields}\n },\n },\n];\n\nexport const editable = buildPageEditable([\n {\n schema: ${slug}Editable,\n prefix: '${slug}_',\n rename: {\n${renameFields}\n },\n },\n]);\n\nexport const defaults = getEditableDefaults(editable);\n`;
163
+
164
+ const schemaSource = `/**\n * ${componentName} — canonical section content contract.\n *\n * Compose this schema into cms/editables/${pageSlug}.ts for baked-page ACF\n * fields, then reuse it from the section component and generated block.\n */\nimport {\n ${imports},\n} from '@forgewp/react';\n\nexport const editable = defineEditable({\n${fieldDefinitions}\n});\n\nexport const defaults = getEditableDefaults(editable);\n`;
165
+
166
+ const fieldTypes = {
167
+ text: 'string',
168
+ richText: 'string',
169
+ image: 'string',
170
+ color: 'string',
171
+ url: 'string',
172
+ select: 'string',
173
+ icon: 'string',
174
+ boolean: 'boolean',
175
+ number: 'number',
176
+ repeater: 'unknown[]',
177
+ };
178
+ const props = fields
179
+ .map(({ name, type }) => ` ${name}?: ${fieldTypes[type]};`)
180
+ .join('\n');
181
+ const resolvedValues = fields
182
+ .map(
183
+ ({ name }) =>
184
+ ` const ${name}Meta = useWpMeta('${slug}_${toSnakeCase(name)}', defaults.${slug}_${toSnakeCase(name)});\n const ${name} = ${name}Prop ?? ${name}Meta;`,
185
+ )
186
+ .join('\n');
187
+ const renderedFields = fields
188
+ .map(({ name, type }) => {
189
+ if (type !== 'text' && type !== 'richText') {
190
+ return ` <div data-field='${name}'>{String(${name})}</div>`;
191
+ }
192
+ const tagName = type === 'richText' ? 'p' : 'h2';
193
+ return ` {setAttributes ? (\n <WpEditable\n tagName='${tagName}'\n value={${name}}\n onChange={(value) => setAttributes({ ${name}: value })}\n />\n ) : (\n <${tagName}>{${name}}</${tagName}>\n )}`;
194
+ })
195
+ .join('\n');
196
+ const propDestructuring = fields
197
+ .map(({ name }) => ` ${name}: ${name}Prop,`)
198
+ .join('\n');
199
+ const blockAnnotation = withBlock
200
+ ? `/**\n * @forgewp-block\n * title: ${componentName.replace(/([A-Z])/g, ' $1').trim()}\n * category: theme\n * description: Editable ${slug} section.\n */\n`
201
+ : '';
202
+
203
+ const componentSource = `import { pickEditable, useWpMeta, WpEditable } from '@forgewp/react';\nimport { editable as pageEditable, defaults } from '../../cms/editables/${pageSlug}';\n\nexport const editable = pickEditable(pageEditable, {\n${pageFields}\n});\n\nexport interface ${componentName}Props {\n${props}\n setAttributes?: (attributes: Partial<${componentName}Props>) => void;\n}\n\n${blockAnnotation}export function ${componentName}({\n${propDestructuring}\n setAttributes,\n}: ${componentName}Props) {\n${resolvedValues}\n\n return (\n <section>\n${renderedFields}\n </section>\n );\n}\n\nexport default ${componentName};\n`;
204
+
205
+ writeFileSync(schemaFile, schemaSource, 'utf8');
206
+ if (!existsSync(pageFile)) {
207
+ writeFileSync(pageFile, pageSchemaSource, 'utf8');
208
+ }
209
+ writeFileSync(componentFile, componentSource, 'utf8');
210
+
211
+ console.log(pc.green(`\n⚡ Section "${componentName}" created.`));
212
+ console.log(` Schema: ${pc.cyan(path.relative(projectRoot, schemaFile))}`);
213
+ console.log(` Page: ${pc.cyan(path.relative(projectRoot, pageFile))}`);
214
+ console.log(
215
+ ` Component: ${pc.cyan(path.relative(projectRoot, componentFile))}`,
216
+ );
217
+ console.log(
218
+ pageExists
219
+ ? '\nThe existing page contract was preserved; add this section to its composition if needed.'
220
+ : '\nThe page contract was created and composed with this section.',
221
+ );
@@ -0,0 +1,375 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * forgewp make:shell
5
+ *
6
+ * Scaffold a parent shell block (InnerBlocks layout wrapper).
7
+ * Interactively lists project blocks so you can pick default children.
8
+ *
9
+ * Usage:
10
+ * pnpm forgewp make:shell AboutSplitSection
11
+ * pnpm forgewp make:shell AboutSplitSection --children=about-mission,about-values --layout=2-col
12
+ */
13
+
14
+ import { existsSync } from "node:fs";
15
+ import path from "node:path";
16
+ import readline from "node:readline/promises";
17
+ import { stdin as input, stdout as output } from "node:process";
18
+ import pc from "picocolors";
19
+ import { loadConfig } from "../lib/load-config.js";
20
+ import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
21
+ import {
22
+ discoverProjectBlocks,
23
+ SHELL_LAYOUT_PRESETS,
24
+ DEFAULT_SHELL_CLASSNAME,
25
+ } from "../lib/blocks/discover-blocks.js";
26
+ import { blockAuthoringHelp } from "../lib/block-authoring-help.js";
27
+
28
+ const args = process.argv.slice(2);
29
+
30
+ function getFlag(name) {
31
+ const eq = args.find((a) => a.startsWith(`--${name}=`));
32
+ if (eq) return eq.slice(name.length + 3);
33
+ const idx = args.indexOf(`--${name}`);
34
+ if (idx !== -1 && args[idx + 1] && !args[idx + 1].startsWith("-")) {
35
+ return args[idx + 1];
36
+ }
37
+ return undefined;
38
+ }
39
+
40
+ function hasFlag(name) {
41
+ return args.includes(`--${name}`) || args.some((a) => a.startsWith(`--${name}=`));
42
+ }
43
+
44
+ function printHelp() {
45
+ console.log(`
46
+ ${pc.bold("forgewp make:shell")} — scaffold a parent shell (InnerBlocks layout)
47
+
48
+ ${pc.bold("Usage:")}
49
+ pnpm forgewp make:shell <Name>
50
+ pnpm forgewp make:shell <Name> --children=block-a,block-b --layout=2-col
51
+
52
+ ${pc.bold("Options:")}
53
+ --name <Name> Shell block name (PascalCase or kebab)
54
+ --children <slugs> Comma-separated child block names (no forgewp/ prefix)
55
+ --layout <preset> ${Object.keys(SHELL_LAYOUT_PRESETS).join(" | ")} | custom
56
+ --grid-class <classes> Override grid className (implies custom layout)
57
+ --class <classes> Outer shell className (default: max-w-7xl + padding)
58
+ --template-lock <mode> false | insert | all | true (default: false)
59
+ --category <slug> Block category (default: theme)
60
+ --icon <dashicon> Dashicon slug (default: columns)
61
+ --description <text> Block description
62
+ --yes Skip interactive prompts when flags provide enough info
63
+ -h, --help Show help
64
+
65
+ ${pc.bold("Examples:")}
66
+ pnpm forgewp make:shell AboutSplitSection
67
+ pnpm forgewp make:shell AboutSplitSection --children=about-mission,about-values --layout=2-col
68
+ pnpm forgewp make:shell FeatureRow --layout=3-col --template-lock=insert
69
+ ${blockAuthoringHelp}
70
+ `);
71
+ }
72
+
73
+ if (hasFlag("help") || args.includes("-h")) {
74
+ printHelp();
75
+ process.exit(0);
76
+ }
77
+
78
+ let rawShellName =
79
+ args.find((a) => !a.startsWith("-")) || getFlag("name") || "";
80
+
81
+ const projectRoot = process.cwd();
82
+ if (!existsSync(path.join(projectRoot, "src"))) {
83
+ console.error(
84
+ pc.red(
85
+ `\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`,
86
+ ),
87
+ );
88
+ process.exit(1);
89
+ }
90
+
91
+ const available = discoverProjectBlocks(projectRoot, { includeShells: false });
92
+
93
+ const rl = readline.createInterface({ input, output });
94
+
95
+ async function ask(prompt, fallback = "") {
96
+ const suffix = fallback !== "" ? pc.dim(` (${fallback})`) : "";
97
+ try {
98
+ const answer = await rl.question(pc.cyan(`? ${prompt}${suffix}: `));
99
+ const t = answer.trim();
100
+ return t || fallback;
101
+ } catch {
102
+ return fallback;
103
+ }
104
+ }
105
+
106
+ try {
107
+ if (!rawShellName) {
108
+ rawShellName = await ask("Shell block name (e.g. AboutSplitSection)");
109
+ }
110
+
111
+ if (!rawShellName) {
112
+ console.error(pc.red("\n❌ Error: Please specify a shell name."));
113
+ console.log(
114
+ pc.cyan(" Example: pnpm forgewp make:shell AboutSplitSection\n"),
115
+ );
116
+ process.exit(1);
117
+ }
118
+
119
+ const cleanName = rawShellName.replace(/[^a-zA-Z0-9_-]/g, "");
120
+ if (!cleanName) {
121
+ console.error(pc.red("\n❌ Error: Invalid shell name.\n"));
122
+ process.exit(1);
123
+ }
124
+
125
+ const pascalCase = cleanName
126
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase())
127
+ .replace(/[^a-zA-Z0-9]/g, "");
128
+
129
+ const nameSlug = pascalCase
130
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
131
+ .toLowerCase()
132
+ .replace(/[^a-z0-9]+/g, "-");
133
+
134
+ const readableTitle = pascalCase
135
+ .replace(/([A-Z])/g, " $1")
136
+ .trim();
137
+
138
+ // ── Children ────────────────────────────────────────────────────────────
139
+ let childrenSlugs = [];
140
+ const childrenFlag = getFlag("children");
141
+ if (childrenFlag !== undefined) {
142
+ childrenSlugs = childrenFlag
143
+ .split(",")
144
+ .map((s) => s.trim().replace(/^forgewp\//, ""))
145
+ .filter(Boolean);
146
+ } else if (!hasFlag("yes")) {
147
+ console.log("");
148
+ if (available.length === 0) {
149
+ console.log(
150
+ pc.yellow(
151
+ " No leaf blocks found yet. Scaffold with make:block / @forgewp-block first,",
152
+ ),
153
+ );
154
+ console.log(
155
+ pc.yellow(
156
+ " or continue with an empty shell (children can be added later).\n",
157
+ ),
158
+ );
159
+ } else {
160
+ console.log(pc.bold(" Available blocks (children candidates):\n"));
161
+ available.forEach((b, i) => {
162
+ console.log(
163
+ ` ${pc.cyan(String(i + 1).padStart(2))}. ${pc.bold(b.name)} ${pc.dim(`— ${b.title}`)} ${pc.dim(`(${b.file})`)}`,
164
+ );
165
+ });
166
+ console.log(
167
+ pc.dim(
168
+ "\n Enter numbers or names, comma-separated. Leave empty for none.\n",
169
+ ),
170
+ );
171
+ const pick = await ask(
172
+ "Child blocks",
173
+ "",
174
+ );
175
+ if (pick) {
176
+ childrenSlugs = resolveChildPicks(pick, available);
177
+ }
178
+ }
179
+ }
180
+
181
+ // Validate children against discovered set (warn only — allows pre-declared slugs)
182
+ const known = new Set(available.map((b) => b.name));
183
+ for (const c of childrenSlugs) {
184
+ if (!known.has(c)) {
185
+ console.log(
186
+ pc.yellow(
187
+ ` ⚠️ "${c}" is not a discovered leaf block — included anyway (ensure it exists at export).`,
188
+ ),
189
+ );
190
+ }
191
+ }
192
+
193
+ // ── Layout ──────────────────────────────────────────────────────────────
194
+ let layoutKey = getFlag("layout") || "";
195
+ let gridClassName = getFlag("grid-class") || getFlag("gridClassName") || "";
196
+ let orientation = "horizontal";
197
+
198
+ if (gridClassName) {
199
+ layoutKey = "custom";
200
+ } else if (!layoutKey && !hasFlag("yes")) {
201
+ console.log(pc.bold("\n Layout presets:\n"));
202
+ const keys = Object.keys(SHELL_LAYOUT_PRESETS);
203
+ keys.forEach((k, i) => {
204
+ console.log(
205
+ ` ${pc.cyan(String(i + 1))}. ${k} — ${SHELL_LAYOUT_PRESETS[k].label}`,
206
+ );
207
+ });
208
+ console.log(` ${pc.cyan(String(keys.length + 1))}. custom — type your own grid classes`);
209
+ const choice = await ask("Layout", "2-col");
210
+ if (/^\d+$/.test(choice)) {
211
+ const n = Number(choice);
212
+ if (n >= 1 && n <= keys.length) layoutKey = keys[n - 1];
213
+ else if (n === keys.length + 1) layoutKey = "custom";
214
+ else layoutKey = "2-col";
215
+ } else {
216
+ layoutKey = choice in SHELL_LAYOUT_PRESETS || choice === "custom"
217
+ ? choice
218
+ : "2-col";
219
+ }
220
+ } else if (!layoutKey) {
221
+ layoutKey = "2-col";
222
+ }
223
+
224
+ if (layoutKey === "custom" && !gridClassName) {
225
+ gridClassName = await ask(
226
+ "Grid className",
227
+ "grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",
228
+ );
229
+ orientation = "horizontal";
230
+ } else if (layoutKey !== "custom") {
231
+ const preset =
232
+ SHELL_LAYOUT_PRESETS[layoutKey] || SHELL_LAYOUT_PRESETS["2-col"];
233
+ gridClassName = preset.gridClassName;
234
+ orientation = preset.orientation || "horizontal";
235
+ }
236
+
237
+ // ── Outer chrome ────────────────────────────────────────────────────────
238
+ let className = getFlag("class") || getFlag("className") || "";
239
+ if (!className && !hasFlag("yes")) {
240
+ className = await ask("Outer shell className", DEFAULT_SHELL_CLASSNAME);
241
+ } else if (!className) {
242
+ className = DEFAULT_SHELL_CLASSNAME;
243
+ }
244
+
245
+ // ── Template lock ───────────────────────────────────────────────────────
246
+ let templateLockRaw =
247
+ getFlag("template-lock") || getFlag("templateLock") || "";
248
+ if (!templateLockRaw && !hasFlag("yes")) {
249
+ templateLockRaw = await ask(
250
+ "templateLock (false | insert | all | true)",
251
+ "false",
252
+ );
253
+ } else if (!templateLockRaw) {
254
+ templateLockRaw = "false";
255
+ }
256
+ const templateLock = parseTemplateLock(templateLockRaw);
257
+
258
+ // ── Meta ────────────────────────────────────────────────────────────────
259
+ let category = getFlag("category") || "";
260
+ if (!category && !hasFlag("yes")) {
261
+ category = await ask("Category", "theme");
262
+ } else if (!category) {
263
+ category = "theme";
264
+ }
265
+
266
+ let icon = getFlag("icon") || "";
267
+ if (!icon && !hasFlag("yes")) {
268
+ icon = await ask("Dashicon", "columns");
269
+ } else if (!icon) {
270
+ icon = "columns";
271
+ }
272
+
273
+ let description =
274
+ getFlag("description") ||
275
+ `Layout shell: ${readableTitle}${childrenSlugs.length ? ` (${childrenSlugs.join(" + ")})` : ""}`;
276
+
277
+ if (!hasFlag("yes") && !getFlag("description")) {
278
+ description = await ask("Description", description);
279
+ }
280
+
281
+ rl.close();
282
+
283
+ // Load adapter
284
+ let frameworkAdapter = "react";
285
+ try {
286
+ const config = await loadConfig(projectRoot);
287
+ frameworkAdapter = config.frameworkAdapter || "react";
288
+ } catch {
289
+ // default
290
+ }
291
+
292
+ const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
293
+ const adapter = adapterModule.default || adapterModule;
294
+
295
+ if (typeof adapter.onMakeShell !== "function") {
296
+ console.error(
297
+ pc.red(
298
+ `\n❌ Error: Framework adapter "${frameworkAdapter}" does not support make:shell.\n`,
299
+ ),
300
+ );
301
+ process.exit(1);
302
+ }
303
+
304
+ await adapter.onMakeShell(projectRoot, {
305
+ pascalCase,
306
+ nameSlug,
307
+ readableTitle,
308
+ childrenSlugs,
309
+ shell: {
310
+ className,
311
+ gridClassName,
312
+ },
313
+ innerBlocks: {
314
+ allowedBlocks: childrenSlugs.length > 0 ? childrenSlugs : undefined,
315
+ template: childrenSlugs.map((slug) => [slug]),
316
+ templateLock,
317
+ orientation,
318
+ },
319
+ category,
320
+ icon,
321
+ description,
322
+ pc,
323
+ });
324
+ } catch (err) {
325
+ try {
326
+ rl.close();
327
+ } catch {
328
+ // ignore
329
+ }
330
+ console.error(
331
+ pc.red(
332
+ `\n❌ Failed to execute make:shell: ${err instanceof Error ? err.message : err}\n`,
333
+ ),
334
+ );
335
+ process.exit(1);
336
+ }
337
+
338
+ /**
339
+ * @param {string} pick
340
+ * @param {import('../lib/blocks/discover-blocks.js').DiscoveredBlock[]} available
341
+ */
342
+ function resolveChildPicks(pick, available) {
343
+ const parts = pick.split(/[,\s]+/).map((p) => p.trim()).filter(Boolean);
344
+ const out = [];
345
+ const seen = new Set();
346
+ for (const p of parts) {
347
+ if (/^\d+$/.test(p)) {
348
+ const idx = Number(p) - 1;
349
+ if (idx >= 0 && idx < available.length) {
350
+ const name = available[idx].name;
351
+ if (!seen.has(name)) {
352
+ seen.add(name);
353
+ out.push(name);
354
+ }
355
+ } else {
356
+ console.log(pc.yellow(` ⚠️ Ignoring out-of-range index: ${p}`));
357
+ }
358
+ continue;
359
+ }
360
+ const slug = p.replace(/^forgewp\//, "");
361
+ if (!seen.has(slug)) {
362
+ seen.add(slug);
363
+ out.push(slug);
364
+ }
365
+ }
366
+ return out;
367
+ }
368
+
369
+ function parseTemplateLock(raw) {
370
+ const v = String(raw).trim().toLowerCase();
371
+ if (v === "false" || v === "0" || v === "no" || v === "none") return false;
372
+ if (v === "true" || v === "1" || v === "yes") return true;
373
+ if (v === "all" || v === "insert") return v;
374
+ return false;
375
+ }
package/bin/repair.js CHANGED
@@ -15,6 +15,13 @@ try {
15
15
  for (const [relativePath, blueprintContent] of Object.entries(SYSTEM_BLUEPRINTS)) {
16
16
  const fullPath = path.join(projectRoot, relativePath);
17
17
 
18
+ if (relativePath.startsWith("cms/") && relativePath.endsWith(".json")) {
19
+ const tsVariant = fullPath.replace(/\.json$/, ".ts");
20
+ if (existsSync(tsVariant)) {
21
+ continue; // Typed .ts file exists, do not overwrite with .json blueprint
22
+ }
23
+ }
24
+
18
25
  // Ensure the folder exists
19
26
  const dirPath = path.dirname(fullPath);
20
27
  if (!existsSync(dirPath)) {
@@ -28,35 +35,16 @@ try {
28
35
  }
29
36
 
30
37
  // Ensure default mock data table is recreated if deleted
31
- const mockDataPath = path.join(projectRoot, "cms", "mock-data.json");
32
- if (!existsSync(mockDataPath)) {
33
- const defaultJson = {
34
- menu: {
35
- primary: [
36
- { title: "Home", url: "/" },
37
- { title: "Blog", url: "/post" },
38
- { title: "Archive", url: "/archive" }
39
- ]
40
- },
41
- post: [
42
- {
43
- id: 1,
44
- title: "Welcome to ForgeWP: The Headless Revolution",
45
- excerpt: "Discover how ForgeWP bridges standard WordPress themes with React.",
46
- content: "<p>Welcome to ForgeWP! Modify this in mock-data.json.</p>",
47
- date: "May 10, 2026",
48
- author: "Antigravity",
49
- featuredImage: "https://picsum.photos/seed/forgewp/1200/630",
50
- customFields: {}
51
- }
52
- ]
53
- };
54
- const dirPath = path.dirname(mockDataPath);
38
+ const mockDataTsPath = path.join(projectRoot, "cms", "mock-data.ts");
39
+ const mockDataJsonPath = path.join(projectRoot, "cms", "mock-data.json");
40
+ if (!existsSync(mockDataTsPath) && !existsSync(mockDataJsonPath)) {
41
+ const defaultTs = `import { defineWpPosts } from '@forgewp/react';\n\nexport const mockData = defineWpPosts({\n post: [\n {\n id: 1,\n title: "Welcome to ForgeWP: The Headless Revolution",\n excerpt: "Discover how ForgeWP bridges standard WordPress themes with React.",\n content: "<p>Welcome to ForgeWP! Modify this in cms/mock-data.ts.</p>",\n date: "May 10, 2026",\n author: "Antigravity",\n featuredImage: "https://picsum.photos/seed/forgewp/1200/630",\n customFields: {}\n }\n ]\n});\n\nexport default mockData;\n`;
42
+ const dirPath = path.dirname(mockDataTsPath);
55
43
  if (!existsSync(dirPath)) {
56
44
  mkdirSync(dirPath, { recursive: true });
57
45
  }
58
- writeFileSync(mockDataPath, JSON.stringify(defaultJson, null, 2), "utf8");
59
- console.log(` ${pc.green("✅ Seeded Default Database")}: cms/mock-data.json`);
46
+ writeFileSync(mockDataTsPath, defaultTs, "utf8");
47
+ console.log(` ${pc.green("✅ Seeded Default Database")}: cms/mock-data.ts`);
60
48
  repairedCount++;
61
49
  }
62
50