@wp-typia/project-tools 0.22.2 → 0.22.3

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 (30) hide show
  1. package/dist/runtime/built-in-block-code-templates/interactivity.d.ts +1 -1
  2. package/dist/runtime/built-in-block-code-templates/interactivity.js +4 -2
  3. package/dist/runtime/cli-add-shared.d.ts +49 -0
  4. package/dist/runtime/cli-add-shared.js +204 -71
  5. package/dist/runtime/cli-add-workspace-ability-scaffold.d.ts +5 -0
  6. package/dist/runtime/cli-add-workspace-ability-scaffold.js +392 -0
  7. package/dist/runtime/cli-add-workspace-ability-templates.d.ts +34 -0
  8. package/dist/runtime/cli-add-workspace-ability-templates.js +500 -0
  9. package/dist/runtime/cli-add-workspace-ability-types.d.ts +27 -0
  10. package/dist/runtime/cli-add-workspace-ability-types.js +14 -0
  11. package/dist/runtime/cli-add-workspace-ability.js +12 -852
  12. package/dist/runtime/cli-add-workspace-ai-scaffold.d.ts +21 -0
  13. package/dist/runtime/cli-add-workspace-ai-scaffold.js +91 -0
  14. package/dist/runtime/cli-add-workspace-ai-templates.d.ts +4 -0
  15. package/dist/runtime/cli-add-workspace-ai-templates.js +605 -0
  16. package/dist/runtime/cli-add-workspace-ai.js +15 -688
  17. package/dist/runtime/cli-add-workspace-assets.js +7 -4
  18. package/dist/runtime/cli-add-workspace.js +1 -19
  19. package/dist/runtime/cli-doctor-workspace-bindings.d.ts +11 -0
  20. package/dist/runtime/cli-doctor-workspace-bindings.js +134 -0
  21. package/dist/runtime/cli-doctor-workspace-blocks.d.ts +11 -0
  22. package/dist/runtime/cli-doctor-workspace-blocks.js +504 -0
  23. package/dist/runtime/cli-doctor-workspace-features.d.ts +11 -0
  24. package/dist/runtime/cli-doctor-workspace-features.js +383 -0
  25. package/dist/runtime/cli-doctor-workspace-package.d.ts +18 -0
  26. package/dist/runtime/cli-doctor-workspace-package.js +59 -0
  27. package/dist/runtime/cli-doctor-workspace-shared.d.ts +69 -0
  28. package/dist/runtime/cli-doctor-workspace-shared.js +87 -0
  29. package/dist/runtime/cli-doctor-workspace.js +25 -1062
  30. package/package.json +3 -3
@@ -1,615 +1,8 @@
1
- import { promises as fsp } from "node:fs";
2
- import path from "node:path";
3
- import { assertAiFeatureDoesNotExist, assertValidGeneratedSlug, getWorkspaceBootstrapPath, normalizeBlockSlug, patchFile, resolveRestResourceNamespace, rollbackWorkspaceMutation, snapshotWorkspaceFiles, } from "./cli-add-shared.js";
4
- import { ensureBlockConfigCanAddRestManifests } from "./cli-add-block-legacy-validator.js";
5
- import { buildAiFeatureConfigEntry, buildAiFeatureDataSource, buildAiFeatureSyncScriptSource, buildAiFeatureTypesSource, buildAiFeatureValidatorsSource, buildAiFeatureApiSource, } from "./cli-add-workspace-ai-source-emitters.js";
6
- import { ensureAiFeatureBootstrapAnchors, ensureAiFeaturePackageScripts, ensureAiFeatureSyncProjectAnchors, ensureAiFeatureSyncRestAnchors, } from "./cli-add-workspace-ai-anchors.js";
7
- import { syncAiFeatureRestArtifacts, syncAiFeatureSchemaArtifact, } from "./ai-feature-artifacts.js";
8
- import { appendWorkspaceInventoryEntries, readWorkspaceInventory } from "./workspace-inventory.js";
1
+ import { assertAiFeatureDoesNotExist, assertValidGeneratedSlug, normalizeBlockSlug, resolveRestResourceNamespace, } from "./cli-add-shared.js";
2
+ import { scaffoldAiFeatureWorkspace } from "./cli-add-workspace-ai-scaffold.js";
3
+ import { readWorkspaceInventory } from "./workspace-inventory.js";
9
4
  import { resolveWorkspaceProject } from "./workspace-project.js";
10
- import { OPTIONAL_WORDPRESS_AI_CLIENT_COMPATIBILITY, resolveScaffoldCompatibilityPolicy, updatePluginHeaderCompatibility, } from "./scaffold-compatibility.js";
11
- import { quotePhpString } from "./php-utils.js";
12
- import { toPascalCase, toTitleCase } from "./string-case.js";
13
- function buildAiFeaturePhpSource(aiFeatureSlug, namespace, phpPrefix, textDomain) {
14
- const aiFeatureTitle = toTitleCase(aiFeatureSlug);
15
- const aiFeaturePhpId = aiFeatureSlug.replace(/-/g, "_");
16
- const loadSchemaFunctionName = `${phpPrefix}_${aiFeaturePhpId}_load_ai_feature_schema`;
17
- const loadAiSchemaFunctionName = `${phpPrefix}_${aiFeaturePhpId}_load_ai_response_schema`;
18
- const normalizeSchemaFunctionName = `${phpPrefix}_${aiFeaturePhpId}_sanitize_ai_feature_schema`;
19
- const validatePayloadFunctionName = `${phpPrefix}_${aiFeaturePhpId}_validate_ai_feature_payload`;
20
- const canManageFunctionName = `${phpPrefix}_${aiFeaturePhpId}_can_manage_ai_feature`;
21
- const normalizePromptPayloadFunctionName = `${phpPrefix}_${aiFeaturePhpId}_normalize_ai_feature_prompt_payload`;
22
- const buildPromptFunctionName = `${phpPrefix}_${aiFeaturePhpId}_build_ai_feature_prompt`;
23
- const resolvePromptOptionsFunctionName = `${phpPrefix}_${aiFeaturePhpId}_resolve_ai_feature_prompt_options`;
24
- const normalizeProviderTypeFunctionName = `${phpPrefix}_${aiFeaturePhpId}_normalize_provider_type`;
25
- const buildTelemetryFunctionName = `${phpPrefix}_${aiFeaturePhpId}_build_ai_feature_telemetry`;
26
- const resolveUnavailableMessageFunctionName = `${phpPrefix}_${aiFeaturePhpId}_resolve_ai_feature_unavailable_message`;
27
- const isSupportedFunctionName = `${phpPrefix}_${aiFeaturePhpId}_is_ai_feature_supported`;
28
- const adminNoticeFunctionName = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_admin_notice`;
29
- const handlerFunctionName = `${phpPrefix}_${aiFeaturePhpId}_handle_run_ai_feature`;
30
- const registerRoutesFunctionName = `${phpPrefix}_${aiFeaturePhpId}_register_ai_feature_routes`;
31
- const permissionFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_permission`;
32
- const promptPayloadFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_prompt_payload`;
33
- const promptFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_prompt`;
34
- const promptOptionsFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_prompt_options`;
35
- const adminNoticeMessageFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_admin_notice_message`;
36
- const unavailableMessageFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_unavailable_message`;
37
- const telemetryFilterHook = `${phpPrefix}_${aiFeaturePhpId}_ai_feature_telemetry`;
38
- return `<?php
39
- if ( ! defined( 'ABSPATH' ) ) {
40
- \treturn;
41
- }
42
-
43
- /*
44
- * Customization hooks for the ${aiFeatureTitle} AI feature:
45
- *
46
- * - ${quotePhpString(permissionFilterHook)} filters the default current_user_can( 'edit_posts' ) capability check.
47
- * - ${quotePhpString(promptPayloadFilterHook)} filters the validated request payload array before prompt serialization.
48
- * - ${quotePhpString(promptFilterHook)} filters the final prompt string after payload normalization.
49
- * - ${quotePhpString(promptOptionsFilterHook)} filters prompt options with \`temperature\` and \`modelPreference\` keys.
50
- * - ${quotePhpString(adminNoticeMessageFilterHook)} filters the wp-admin notice shown when AI support is unavailable.
51
- * - ${quotePhpString(unavailableMessageFilterHook)} filters REST-facing unavailable messages by reason code.
52
- * - ${quotePhpString(telemetryFilterHook)} filters the response telemetry array before schema validation. Return a schema-compatible array.
53
- */
54
-
55
- if ( ! function_exists( '${loadSchemaFunctionName}' ) ) {
56
- \tfunction ${loadSchemaFunctionName}( $schema_name ) {
57
- \t\t$project_root = dirname( __DIR__, 2 );
58
- \t\t$schema_path = $project_root . '/src/ai-features/${aiFeatureSlug}/api-schemas/' . $schema_name . '.schema.json';
59
- \t\tif ( ! file_exists( $schema_path ) ) {
60
- \t\t\treturn null;
61
- \t\t}
62
-
63
- \t\t$decoded = json_decode( file_get_contents( $schema_path ), true );
64
- \t\treturn is_array( $decoded ) ? $decoded : null;
65
- \t}
66
- }
67
-
68
- if ( ! function_exists( '${loadAiSchemaFunctionName}' ) ) {
69
- \tfunction ${loadAiSchemaFunctionName}() {
70
- \t\t$project_root = dirname( __DIR__, 2 );
71
- \t\t$schema_path = $project_root . '/src/ai-features/${aiFeatureSlug}/ai-schemas/feature-result.ai.schema.json';
72
- \t\tif ( ! file_exists( $schema_path ) ) {
73
- \t\t\treturn null;
74
- \t\t}
75
-
76
- \t\t$decoded = json_decode( file_get_contents( $schema_path ), true );
77
- \t\treturn is_array( $decoded ) ? $decoded : null;
78
- \t}
79
- }
80
-
81
- if ( ! function_exists( '${normalizeSchemaFunctionName}' ) ) {
82
- \tfunction ${normalizeSchemaFunctionName}( $schema ) {
83
- \t\tif ( ! is_array( $schema ) ) {
84
- \t\t\treturn $schema;
85
- \t\t}
86
-
87
- \t\tunset( $schema['$schema'], $schema['title'] );
88
-
89
- \t\tif ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) {
90
- \t\t\tforeach ( $schema['properties'] as $key => $property_schema ) {
91
- \t\t\t\t$schema['properties'][ $key ] = ${normalizeSchemaFunctionName}( $property_schema );
92
- \t\t\t}
93
- \t\t}
94
-
95
- \t\tif ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) {
96
- \t\t\t$schema['items'] = ${normalizeSchemaFunctionName}( $schema['items'] );
97
- \t\t}
98
-
99
- \t\treturn $schema;
100
- \t}
101
- }
102
-
103
- if ( ! function_exists( '${validatePayloadFunctionName}' ) ) {
104
- \tfunction ${validatePayloadFunctionName}( $value, $schema_name, $param_name ) {
105
- \t\t$schema = ${loadSchemaFunctionName}( $schema_name );
106
- \t\tif ( ! is_array( $schema ) ) {
107
- \t\t\treturn new WP_Error( 'missing_schema', 'Missing AI feature schema.', array( 'status' => 500 ) );
108
- \t\t}
109
-
110
- \t\t$rest_schema = ${normalizeSchemaFunctionName}( $schema );
111
- \t\t$validation = rest_validate_value_from_schema( $value, $rest_schema, $param_name );
112
- \t\tif ( is_wp_error( $validation ) ) {
113
- \t\t\treturn $validation;
114
- \t\t}
115
-
116
- \t\treturn rest_sanitize_value_from_schema( $value, $rest_schema, $param_name );
117
- \t}
118
- }
119
-
120
- if ( ! function_exists( '${canManageFunctionName}' ) ) {
121
- \tfunction ${canManageFunctionName}( WP_REST_Request $request = null ) {
122
- \t\t$permission = apply_filters(
123
- \t\t\t${quotePhpString(permissionFilterHook)},
124
- \t\t\tcurrent_user_can( 'edit_posts' ),
125
- \t\t\t$request
126
- \t\t);
127
- \t\tif ( is_wp_error( $permission ) ) {
128
- \t\t\treturn $permission;
129
- \t\t}
130
- \t\treturn (bool) $permission;
131
- \t}
132
- }
133
-
134
- if ( ! function_exists( '${normalizePromptPayloadFunctionName}' ) ) {
135
- \tfunction ${normalizePromptPayloadFunctionName}( array $payload ) {
136
- \t\t$normalized_payload = apply_filters(
137
- \t\t\t${quotePhpString(promptPayloadFilterHook)},
138
- \t\t\t$payload
139
- \t\t);
140
- \t\treturn is_array( $normalized_payload ) ? $normalized_payload : $payload;
141
- \t}
142
- }
143
-
144
- if ( ! function_exists( '${buildPromptFunctionName}' ) ) {
145
- \tfunction ${buildPromptFunctionName}( array $payload ) {
146
- \t\t$normalized_payload = ${normalizePromptPayloadFunctionName}( $payload );
147
- \t\t$prompt = sprintf(
148
- \t\t\t'You are helping with the %1$s AI workflow. Read the JSON request payload and return JSON that matches the provided schema. Request payload: %2$s',
149
- \t\t\t${quotePhpString(aiFeatureTitle)},
150
- \t\t\twp_json_encode( $normalized_payload )
151
- \t\t);
152
- \t\t$filtered_prompt = apply_filters(
153
- \t\t\t${quotePhpString(promptFilterHook)},
154
- \t\t\t$prompt,
155
- \t\t\t$normalized_payload,
156
- \t\t\t$payload
157
- \t\t);
158
- \t\treturn is_string( $filtered_prompt ) && '' !== $filtered_prompt ? $filtered_prompt : $prompt;
159
- \t}
160
- }
161
-
162
- if ( ! function_exists( '${resolvePromptOptionsFunctionName}' ) ) {
163
- \tfunction ${resolvePromptOptionsFunctionName}( array $payload = array() ) {
164
- \t\t$options = apply_filters(
165
- \t\t\t${quotePhpString(promptOptionsFilterHook)},
166
- \t\t\tarray(
167
- \t\t\t\t'modelPreference' => array(),
168
- \t\t\t\t'temperature' => 0.2,
169
- \t\t\t),
170
- \t\t\t$payload
171
- \t\t);
172
- \t\tif ( ! is_array( $options ) ) {
173
- \t\t\t$options = array();
174
- \t\t}
175
-
176
- \t\t$temperature = 0.2;
177
- \t\tif ( array_key_exists( 'temperature', $options ) ) {
178
- \t\t\tif ( null === $options['temperature'] ) {
179
- \t\t\t\t$temperature = null;
180
- \t\t\t} elseif ( is_numeric( $options['temperature'] ) ) {
181
- \t\t\t\t$temperature = (float) $options['temperature'];
182
- \t\t\t}
183
- \t\t}
184
-
185
- \t\t$model_preferences = array();
186
- \t\tif ( isset( $options['modelPreference'] ) ) {
187
- \t\t\t$raw_model_preferences = $options['modelPreference'];
188
- \t\t\tif ( is_string( $raw_model_preferences ) && '' !== $raw_model_preferences ) {
189
- \t\t\t\t$model_preferences = array( $raw_model_preferences );
190
- \t\t\t} elseif ( is_array( $raw_model_preferences ) ) {
191
- \t\t\t\t$model_preferences = array_values(
192
- \t\t\t\t\tarray_filter(
193
- \t\t\t\t\t\tarray_map(
194
- \t\t\t\t\t\t\tstatic function ( $candidate ) {
195
- \t\t\t\t\t\t\t\tif ( is_string( $candidate ) && '' !== $candidate ) {
196
- \t\t\t\t\t\t\t\t\treturn $candidate;
197
- \t\t\t\t\t\t\t\t}
198
- \t\t\t\t\t\t\t\tif ( ! is_array( $candidate ) ) {
199
- \t\t\t\t\t\t\t\t\treturn null;
200
- \t\t\t\t\t\t\t\t}
201
-
202
- \t\t\t\t\t\t\t\t$normalized = array_values(
203
- \t\t\t\t\t\t\t\t\tarray_filter(
204
- \t\t\t\t\t\t\t\t\t\t$candidate,
205
- \t\t\t\t\t\t\t\t\t\tstatic function ( $value ) {
206
- \t\t\t\t\t\t\t\t\t\t\treturn is_string( $value ) && '' !== $value;
207
- \t\t\t\t\t\t\t\t\t\t}
208
- \t\t\t\t\t\t\t\t\t)
209
- \t\t\t\t\t\t\t\t);
210
-
211
- \t\t\t\t\t\t\t\treturn count( $normalized ) > 0 ? $normalized : null;
212
- \t\t\t\t\t\t\t},
213
- \t\t\t\t\t\t\t$raw_model_preferences
214
- \t\t\t\t\t\t),
215
- \t\t\t\t\t\tstatic function ( $candidate ) {
216
- \t\t\t\t\t\t\treturn null !== $candidate;
217
- \t\t\t\t\t\t}
218
- \t\t\t\t\t)
219
- \t\t\t\t);
220
- \t\t\t}
221
- \t\t}
222
-
223
- \t\treturn array(
224
- \t\t\t'modelPreference' => $model_preferences,
225
- \t\t\t'temperature' => $temperature,
226
- \t\t);
227
- \t}
228
- }
229
-
230
- if ( ! function_exists( '${normalizeProviderTypeFunctionName}' ) ) {
231
- \tfunction ${normalizeProviderTypeFunctionName}( $provider_type ) {
232
- \t\tif ( is_object( $provider_type ) && isset( $provider_type->value ) && is_string( $provider_type->value ) ) {
233
- \t\t\treturn $provider_type->value;
234
- \t\t}
235
-
236
- \t\treturn is_string( $provider_type ) && '' !== $provider_type ? $provider_type : 'cloud';
237
- \t}
238
- }
239
-
240
- if ( ! function_exists( '${buildTelemetryFunctionName}' ) ) {
241
- \tfunction ${buildTelemetryFunctionName}( $result, array $payload = array(), array $normalized_result = array() ) {
242
- \t\tif (
243
- \t\t\t! is_object( $result ) ||
244
- \t\t\t! method_exists( $result, 'getId' ) ||
245
- \t\t\t! method_exists( $result, 'getModelMetadata' ) ||
246
- \t\t\t! method_exists( $result, 'getProviderMetadata' ) ||
247
- \t\t\t! method_exists( $result, 'getTokenUsage' )
248
- \t\t) {
249
- \t\t\treturn new WP_Error(
250
- \t\t\t\t'ai_client_result_shape',
251
- \t\t\t\t'The current WordPress AI Client result object is missing telemetry helpers.',
252
- \t\t\t\tarray( 'status' => 502 )
253
- \t\t\t);
254
- \t\t}
255
-
256
- \t\t$model_metadata = $result->getModelMetadata();
257
- \t\t$provider_metadata = $result->getProviderMetadata();
258
- \t\t$token_usage = $result->getTokenUsage();
259
-
260
- \t\tif (
261
- \t\t\t! is_object( $model_metadata ) ||
262
- \t\t\t! method_exists( $model_metadata, 'getId' ) ||
263
- \t\t\t! method_exists( $model_metadata, 'getName' ) ||
264
- \t\t\t! is_object( $provider_metadata ) ||
265
- \t\t\t! method_exists( $provider_metadata, 'getId' ) ||
266
- \t\t\t! method_exists( $provider_metadata, 'getName' ) ||
267
- \t\t\t! method_exists( $provider_metadata, 'getType' ) ||
268
- \t\t\t! is_object( $token_usage ) ||
269
- \t\t\t! method_exists( $token_usage, 'getCompletionTokens' ) ||
270
- \t\t\t! method_exists( $token_usage, 'getPromptTokens' ) ||
271
- \t\t\t! method_exists( $token_usage, 'getTotalTokens' )
272
- \t\t) {
273
- \t\t\treturn new WP_Error(
274
- \t\t\t\t'ai_client_result_shape',
275
- \t\t\t\t'The current WordPress AI Client telemetry objects are missing expected getters.',
276
- \t\t\t\tarray( 'status' => 502 )
277
- \t\t\t);
278
- \t\t}
279
-
280
- \t\t$telemetry = array(
281
- \t\t\t'modelId' => (string) $model_metadata->getId(),
282
- \t\t\t'modelName' => (string) $model_metadata->getName(),
283
- \t\t\t'providerId' => (string) $provider_metadata->getId(),
284
- \t\t\t'providerName' => (string) $provider_metadata->getName(),
285
- \t\t\t'providerType' => ${normalizeProviderTypeFunctionName}( $provider_metadata->getType() ),
286
- \t\t\t'resultId' => (string) $result->getId(),
287
- \t\t\t'tokenUsage' => array(
288
- \t\t\t\t'completionTokens' => (int) $token_usage->getCompletionTokens(),
289
- \t\t\t\t'promptTokens' => (int) $token_usage->getPromptTokens(),
290
- \t\t\t\t'totalTokens' => (int) $token_usage->getTotalTokens(),
291
- \t\t\t),
292
- \t\t);
293
-
294
- \t\tif ( method_exists( $token_usage, 'getThoughtTokens' ) ) {
295
- \t\t\t$thought_tokens = $token_usage->getThoughtTokens();
296
- \t\t\tif ( null !== $thought_tokens ) {
297
- \t\t\t\t$telemetry['tokenUsage']['thoughtTokens'] = (int) $thought_tokens;
298
- \t\t\t}
299
- \t\t}
300
-
301
- \t\t$filtered_telemetry = apply_filters(
302
- \t\t\t${quotePhpString(telemetryFilterHook)},
303
- \t\t\t$telemetry,
304
- \t\t\t$result,
305
- \t\t\t$payload,
306
- \t\t\t$normalized_result
307
- \t\t);
308
- \t\treturn is_array( $filtered_telemetry ) ? $filtered_telemetry : $telemetry;
309
- \t}
310
- }
311
-
312
- if ( ! function_exists( '${resolveUnavailableMessageFunctionName}' ) ) {
313
- \tfunction ${resolveUnavailableMessageFunctionName}( $message, $reason, array $context = array() ) {
314
- \t\t$filtered_message = apply_filters(
315
- \t\t\t${quotePhpString(unavailableMessageFilterHook)},
316
- \t\t\t$message,
317
- \t\t\t$reason,
318
- \t\t\t$context
319
- \t\t);
320
- \t\treturn is_string( $filtered_message ) && '' !== $filtered_message ? $filtered_message : $message;
321
- \t}
322
- }
323
-
324
- if ( ! function_exists( '${isSupportedFunctionName}' ) ) {
325
- \tfunction ${isSupportedFunctionName}( array $payload = array(), $cache_result = true ) {
326
- \t\tstatic $is_supported = null;
327
- \t\t$use_cache = $cache_result && count( $payload ) === 0;
328
- \t\tif ( $use_cache && null !== $is_supported ) {
329
- \t\t\treturn $is_supported;
330
- \t\t}
331
-
332
- \t\tif ( ! function_exists( 'wp_ai_client_prompt' ) ) {
333
- \t\t\tif ( $use_cache ) {
334
- \t\t\t\t$is_supported = false;
335
- \t\t\t}
336
- \t\t\treturn false;
337
- \t\t}
338
-
339
- \t\t$schema = ${loadAiSchemaFunctionName}();
340
- \t\tif ( ! is_array( $schema ) ) {
341
- \t\t\tif ( $use_cache ) {
342
- \t\t\t\t$is_supported = false;
343
- \t\t\t}
344
- \t\t\treturn false;
345
- \t\t}
346
-
347
- \t\t$prompt = wp_ai_client_prompt( 'AI feature support probe.' );
348
- \t\tif ( ! is_object( $prompt ) || ! method_exists( $prompt, 'as_json_response' ) ) {
349
- \t\t\tif ( $use_cache ) {
350
- \t\t\t\t$is_supported = false;
351
- \t\t\t}
352
- \t\t\treturn false;
353
- \t\t}
354
- \t\t$prompt_options = ${resolvePromptOptionsFunctionName}( $payload );
355
- \t\tif (
356
- \t\t\tarray_key_exists( 'temperature', $prompt_options ) &&
357
- \t\t\tnull !== $prompt_options['temperature'] &&
358
- \t\t\tmethod_exists( $prompt, 'using_temperature' )
359
- \t\t) {
360
- \t\t\t$prompt = $prompt->using_temperature( $prompt_options['temperature'] );
361
- \t\t}
362
- \t\tif (
363
- \t\t\t! empty( $prompt_options['modelPreference'] ) &&
364
- \t\t\tmethod_exists( $prompt, 'using_model_preference' )
365
- \t\t) {
366
- \t\t\t$prompt = $prompt->using_model_preference( ...$prompt_options['modelPreference'] );
367
- \t\t}
368
-
369
- \t\t$structured_prompt = $prompt->as_json_response( $schema );
370
- \t\tif ( ! is_object( $structured_prompt ) ) {
371
- \t\t\tif ( $use_cache ) {
372
- \t\t\t\t$is_supported = false;
373
- \t\t\t}
374
- \t\t\treturn false;
375
- \t\t}
376
-
377
- \t\tif ( method_exists( $structured_prompt, 'is_supported_for_text_generation' ) ) {
378
- \t\t\t$supported = (bool) $structured_prompt->is_supported_for_text_generation();
379
- \t\t\tif ( $use_cache ) {
380
- \t\t\t\t$is_supported = $supported;
381
- \t\t\t}
382
- \t\t\treturn $supported;
383
- \t\t}
384
-
385
- \t\t$supported = method_exists( $structured_prompt, 'generate_text_result' );
386
- \t\tif ( $use_cache ) {
387
- \t\t\t$is_supported = $supported;
388
- \t\t}
389
- \t\treturn $supported;
390
- \t}
391
- }
392
-
393
- if ( ! function_exists( '${adminNoticeFunctionName}' ) ) {
394
- \tfunction ${adminNoticeFunctionName}() {
395
- \t\tif ( ! current_user_can( 'manage_options' ) || ${isSupportedFunctionName}() ) {
396
- \t\t\treturn;
397
- \t\t}
398
-
399
- \t\t$message = sprintf(
400
- \t\t\t/* translators: %s: AI feature name. */
401
- \t\t\t__( 'The %s AI feature is optional and remains disabled until the WordPress AI Client is available with structured text generation support for the generated schema.', ${quotePhpString(textDomain)} ),
402
- \t\t\t${quotePhpString(aiFeatureTitle)}
403
- \t\t);
404
- \t\t$filtered_message = apply_filters(
405
- \t\t\t${quotePhpString(adminNoticeMessageFilterHook)},
406
- \t\t\t$message,
407
- \t\t\tarray(
408
- \t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
409
- \t\t\t\t'featureTitle' => ${quotePhpString(aiFeatureTitle)},
410
- \t\t\t\t'namespace' => ${quotePhpString(namespace)},
411
- \t\t\t)
412
- \t\t);
413
- \t\tif ( is_string( $filtered_message ) && '' !== $filtered_message ) {
414
- \t\t\t$message = $filtered_message;
415
- \t\t}
416
- \t\tprintf( '<div class="notice notice-warning"><p>%s</p></div>', esc_html( $message ) );
417
- \t}
418
- }
419
-
420
- if ( ! function_exists( '${handlerFunctionName}' ) ) {
421
- \tfunction ${handlerFunctionName}( WP_REST_Request $request ) {
422
- \t\t$payload = ${validatePayloadFunctionName}( $request->get_json_params(), 'feature-request', 'body' );
423
- \t\tif ( is_wp_error( $payload ) ) {
424
- \t\t\treturn $payload;
425
- \t\t}
426
-
427
- \t\tif ( ! ${isSupportedFunctionName}( $payload, false ) ) {
428
- \t\t\treturn new WP_Error(
429
- \t\t\t\t'ai_client_unavailable',
430
- \t\t\t\t${resolveUnavailableMessageFunctionName}(
431
- \t\t\t\t\t'The WordPress AI Client is unavailable or does not support this feature endpoint.',
432
- \t\t\t\t\t'support_probe_failed',
433
- \t\t\t\t\tarray(
434
- \t\t\t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
435
- \t\t\t\t\t)
436
- \t\t\t\t),
437
- \t\t\t\tarray( 'status' => 501 )
438
- \t\t\t);
439
- \t\t}
440
-
441
- \t\t$ai_schema = ${loadAiSchemaFunctionName}();
442
- \t\tif ( ! is_array( $ai_schema ) ) {
443
- \t\t\treturn new WP_Error(
444
- \t\t\t\t'ai_client_schema_missing',
445
- \t\t\t\t'The generated AI response schema is missing for this feature endpoint.',
446
- \t\t\t\tarray( 'status' => 500 )
447
- \t\t\t);
448
- \t\t}
449
-
450
- \t\t$prompt_options = ${resolvePromptOptionsFunctionName}( $payload );
451
- \t\t$prompt = wp_ai_client_prompt( ${buildPromptFunctionName}( $payload ) );
452
- \t\tif ( ! is_object( $prompt ) ) {
453
- \t\t\treturn new WP_Error(
454
- \t\t\t\t'ai_client_unavailable',
455
- \t\t\t\t${resolveUnavailableMessageFunctionName}(
456
- \t\t\t\t\t'The WordPress AI Client prompt builder is unavailable on this site.',
457
- \t\t\t\t\t'prompt_builder_missing',
458
- \t\t\t\t\tarray(
459
- \t\t\t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
460
- \t\t\t\t\t)
461
- \t\t\t\t),
462
- \t\t\t\tarray( 'status' => 501 )
463
- \t\t\t);
464
- \t\t}
465
-
466
- \t\tif (
467
- \t\t\tarray_key_exists( 'temperature', $prompt_options ) &&
468
- \t\t\tnull !== $prompt_options['temperature'] &&
469
- \t\t\tmethod_exists( $prompt, 'using_temperature' )
470
- \t\t) {
471
- \t\t\t$prompt = $prompt->using_temperature( $prompt_options['temperature'] );
472
- \t\t}
473
- \t\tif (
474
- \t\t\t! empty( $prompt_options['modelPreference'] ) &&
475
- \t\t\tmethod_exists( $prompt, 'using_model_preference' )
476
- \t\t) {
477
- \t\t\t$prompt = $prompt->using_model_preference( ...$prompt_options['modelPreference'] );
478
- \t\t}
479
- \t\tif ( ! method_exists( $prompt, 'as_json_response' ) ) {
480
- \t\t\treturn new WP_Error(
481
- \t\t\t\t'ai_client_unavailable',
482
- \t\t\t\t${resolveUnavailableMessageFunctionName}(
483
- \t\t\t\t\t'The current WordPress AI Client does not expose as_json_response().',
484
- \t\t\t\t\t'as_json_response_missing',
485
- \t\t\t\t\tarray(
486
- \t\t\t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
487
- \t\t\t\t\t)
488
- \t\t\t\t),
489
- \t\t\t\tarray( 'status' => 501 )
490
- \t\t\t);
491
- \t\t}
492
-
493
- \t\t$structured_prompt = $prompt->as_json_response( $ai_schema );
494
- \t\tif ( ! is_object( $structured_prompt ) ) {
495
- \t\t\treturn new WP_Error(
496
- \t\t\t\t'ai_client_unavailable',
497
- \t\t\t\t${resolveUnavailableMessageFunctionName}(
498
- \t\t\t\t\t'The current WordPress AI Client could not prepare a structured-output prompt.',
499
- \t\t\t\t\t'structured_prompt_missing',
500
- \t\t\t\t\tarray(
501
- \t\t\t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
502
- \t\t\t\t\t)
503
- \t\t\t\t),
504
- \t\t\t\tarray( 'status' => 501 )
505
- \t\t\t);
506
- \t\t}
507
-
508
- \t\tif (
509
- \t\t\tmethod_exists( $structured_prompt, 'is_supported_for_text_generation' ) &&
510
- \t\t\t! $structured_prompt->is_supported_for_text_generation()
511
- \t\t) {
512
- \t\t\treturn new WP_Error(
513
- \t\t\t\t'ai_client_unavailable',
514
- \t\t\t\t${resolveUnavailableMessageFunctionName}(
515
- \t\t\t\t\t'The current WordPress AI Client provider or model does not support this structured-output feature.',
516
- \t\t\t\t\t'text_generation_unsupported',
517
- \t\t\t\t\tarray(
518
- \t\t\t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
519
- \t\t\t\t\t)
520
- \t\t\t\t),
521
- \t\t\t\tarray( 'status' => 501 )
522
- \t\t\t);
523
- \t\t}
524
- \t\tif ( ! method_exists( $structured_prompt, 'generate_text_result' ) ) {
525
- \t\t\treturn new WP_Error(
526
- \t\t\t\t'ai_client_unavailable',
527
- \t\t\t\t${resolveUnavailableMessageFunctionName}(
528
- \t\t\t\t\t'The current WordPress AI Client does not expose generate_text_result() after as_json_response().',
529
- \t\t\t\t\t'generate_text_result_missing',
530
- \t\t\t\t\tarray(
531
- \t\t\t\t\t\t'featureSlug' => ${quotePhpString(aiFeatureSlug)},
532
- \t\t\t\t\t)
533
- \t\t\t\t),
534
- \t\t\t\tarray( 'status' => 501 )
535
- \t\t\t);
536
- \t\t}
537
-
538
- \t\t$result = $structured_prompt->generate_text_result();
539
- \t\tif ( is_wp_error( $result ) ) {
540
- \t\t\treturn $result;
541
- \t\t}
542
- \t\tif ( ! is_object( $result ) || ! method_exists( $result, 'toText' ) ) {
543
- \t\t\treturn new WP_Error(
544
- \t\t\t\t'ai_client_result_shape',
545
- \t\t\t\t'The current WordPress AI Client result does not expose toText().',
546
- \t\t\t\tarray( 'status' => 502 )
547
- \t\t\t);
548
- \t\t}
549
-
550
- \t\t$decoded_result = json_decode( $result->toText(), true );
551
- \t\tif ( ! is_array( $decoded_result ) ) {
552
- \t\t\treturn new WP_Error(
553
- \t\t\t\t'ai_client_invalid_json',
554
- \t\t\t\t'The AI feature response did not decode to a JSON object.',
555
- \t\t\t\tarray( 'status' => 502 )
556
- \t\t\t);
557
- \t\t}
558
-
559
- \t\t$normalized_result = ${validatePayloadFunctionName}( $decoded_result, 'feature-result', 'result' );
560
- \t\tif ( is_wp_error( $normalized_result ) ) {
561
- \t\t\treturn new WP_Error(
562
- \t\t\t\t'ai_client_invalid_response',
563
- \t\t\t\t$normalized_result->get_error_message(),
564
- \t\t\t\tarray( 'status' => 502 )
565
- \t\t\t);
566
- \t\t}
567
-
568
- \t\t$telemetry = ${buildTelemetryFunctionName}( $result, $payload, $normalized_result );
569
- \t\tif ( is_wp_error( $telemetry ) ) {
570
- \t\t\treturn $telemetry;
571
- \t\t}
572
-
573
- \t\t$response = ${validatePayloadFunctionName}(
574
- \t\t\tarray(
575
- \t\t\t\t'result' => $normalized_result,
576
- \t\t\t\t'telemetry' => $telemetry,
577
- \t\t\t),
578
- \t\t\t'feature-response',
579
- \t\t\t'response'
580
- \t\t);
581
- \t\tif ( is_wp_error( $response ) ) {
582
- \t\t\treturn new WP_Error(
583
- \t\t\t\t'ai_client_invalid_response',
584
- \t\t\t\t$response->get_error_message(),
585
- \t\t\t\tarray( 'status' => 502 )
586
- \t\t\t);
587
- \t\t}
588
-
589
- \t\treturn rest_ensure_response( $response );
590
- \t}
591
- }
592
-
593
- if ( ! function_exists( '${registerRoutesFunctionName}' ) ) {
594
- \tfunction ${registerRoutesFunctionName}() {
595
- \t\tregister_rest_route(
596
- \t\t\t${quotePhpString(namespace)},
597
- \t\t\t'/ai/${aiFeatureSlug}',
598
- \t\t\tarray(
599
- \t\t\t\tarray(
600
- \t\t\t\t\t'methods' => WP_REST_Server::CREATABLE,
601
- \t\t\t\t\t'callback' => '${handlerFunctionName}',
602
- \t\t\t\t\t'permission_callback' => '${canManageFunctionName}',
603
- \t\t\t\t)
604
- \t\t\t)
605
- \t\t);
606
- \t}
607
- }
608
-
609
- add_action( 'admin_notices', '${adminNoticeFunctionName}' );
610
- add_action( 'rest_api_init', '${registerRoutesFunctionName}' );
611
- `;
612
- }
5
+ import { OPTIONAL_WORDPRESS_AI_CLIENT_COMPATIBILITY, resolveScaffoldCompatibilityPolicy, } from "./scaffold-compatibility.js";
613
6
  /**
614
7
  * Scaffold a workspace-level server-only AI feature endpoint and synchronize
615
8
  * its typed REST plus AI-schema artifacts.
@@ -624,82 +17,16 @@ export async function runAddAiFeatureCommand({ aiFeatureName, cwd = process.cwd(
624
17
  const compatibilityPolicy = resolveScaffoldCompatibilityPolicy(OPTIONAL_WORDPRESS_AI_CLIENT_COMPATIBILITY);
625
18
  const inventory = readWorkspaceInventory(workspace.projectDir);
626
19
  assertAiFeatureDoesNotExist(workspace.projectDir, aiFeatureSlug, inventory);
627
- const blockConfigPath = path.join(workspace.projectDir, "scripts", "block-config.ts");
628
- const bootstrapPath = getWorkspaceBootstrapPath(workspace);
629
- const packageJsonPath = path.join(workspace.projectDir, "package.json");
630
- const syncAiScriptPath = path.join(workspace.projectDir, "scripts", "sync-ai-features.ts");
631
- const syncProjectScriptPath = path.join(workspace.projectDir, "scripts", "sync-project.ts");
632
- const syncRestScriptPath = path.join(workspace.projectDir, "scripts", "sync-rest-contracts.ts");
633
- const aiFeatureDir = path.join(workspace.projectDir, "src", "ai-features", aiFeatureSlug);
634
- const typesFilePath = path.join(aiFeatureDir, "api-types.ts");
635
- const validatorsFilePath = path.join(aiFeatureDir, "api-validators.ts");
636
- const apiFilePath = path.join(aiFeatureDir, "api.ts");
637
- const dataFilePath = path.join(aiFeatureDir, "data.ts");
638
- const phpFilePath = path.join(workspace.projectDir, "inc", "ai-features", `${aiFeatureSlug}.php`);
639
- const mutationSnapshot = {
640
- fileSources: await snapshotWorkspaceFiles([
641
- blockConfigPath,
642
- bootstrapPath,
643
- packageJsonPath,
644
- syncAiScriptPath,
645
- syncProjectScriptPath,
646
- syncRestScriptPath,
647
- ]),
648
- snapshotDirs: [],
649
- targetPaths: [aiFeatureDir, phpFilePath, syncAiScriptPath],
20
+ const scaffoldResult = await scaffoldAiFeatureWorkspace({
21
+ aiFeatureSlug,
22
+ compatibilityPolicy,
23
+ namespace: resolvedNamespace,
24
+ workspace,
25
+ });
26
+ return {
27
+ aiFeatureSlug,
28
+ namespace: resolvedNamespace,
29
+ projectDir: workspace.projectDir,
30
+ warnings: scaffoldResult.warnings,
650
31
  };
651
- try {
652
- await fsp.mkdir(aiFeatureDir, { recursive: true });
653
- await fsp.mkdir(path.dirname(phpFilePath), { recursive: true });
654
- await ensureAiFeatureBootstrapAnchors(workspace);
655
- await patchFile(bootstrapPath, (source) => updatePluginHeaderCompatibility(source, compatibilityPolicy));
656
- const packageScriptChanges = await ensureAiFeaturePackageScripts(workspace);
657
- await ensureAiFeatureSyncProjectAnchors(workspace);
658
- await ensureAiFeatureSyncRestAnchors(workspace);
659
- await fsp.writeFile(syncAiScriptPath, buildAiFeatureSyncScriptSource(), "utf8");
660
- await fsp.writeFile(typesFilePath, buildAiFeatureTypesSource(aiFeatureSlug), "utf8");
661
- await fsp.writeFile(validatorsFilePath, buildAiFeatureValidatorsSource(aiFeatureSlug), "utf8");
662
- await fsp.writeFile(apiFilePath, buildAiFeatureApiSource(aiFeatureSlug), "utf8");
663
- await fsp.writeFile(dataFilePath, buildAiFeatureDataSource(aiFeatureSlug), "utf8");
664
- await fsp.writeFile(phpFilePath, buildAiFeaturePhpSource(aiFeatureSlug, resolvedNamespace, workspace.workspace.phpPrefix, workspace.workspace.textDomain), "utf8");
665
- const pascalCase = toPascalCase(aiFeatureSlug);
666
- await syncAiFeatureRestArtifacts({
667
- clientFile: `src/ai-features/${aiFeatureSlug}/api-client.ts`,
668
- outputDir: path.join("src", "ai-features", aiFeatureSlug),
669
- projectDir: workspace.projectDir,
670
- typesFile: `src/ai-features/${aiFeatureSlug}/api-types.ts`,
671
- validatorsFile: `src/ai-features/${aiFeatureSlug}/api-validators.ts`,
672
- variables: {
673
- namespace: resolvedNamespace,
674
- pascalCase,
675
- slugKebabCase: aiFeatureSlug,
676
- title: toTitleCase(aiFeatureSlug),
677
- },
678
- });
679
- await syncAiFeatureSchemaArtifact({
680
- aiSchemaFile: `src/ai-features/${aiFeatureSlug}/ai-schemas/feature-result.ai.schema.json`,
681
- outputDir: path.join("src", "ai-features", aiFeatureSlug),
682
- projectDir: workspace.projectDir,
683
- });
684
- await appendWorkspaceInventoryEntries(workspace.projectDir, {
685
- aiFeatureEntries: [
686
- buildAiFeatureConfigEntry(aiFeatureSlug, resolvedNamespace),
687
- ],
688
- transformSource: ensureBlockConfigCanAddRestManifests,
689
- });
690
- return {
691
- aiFeatureSlug,
692
- namespace: resolvedNamespace,
693
- projectDir: workspace.projectDir,
694
- warnings: packageScriptChanges.addedProjectToolsDependency
695
- ? [
696
- "Added `@wp-typia/project-tools` to devDependencies for `sync-ai`. If this workspace was already installed, rerun your package manager install command before the first `wp-typia sync ai`.",
697
- ]
698
- : [],
699
- };
700
- }
701
- catch (error) {
702
- await rollbackWorkspaceMutation(mutationSnapshot);
703
- throw error;
704
- }
705
32
  }