@wp-typia/project-tools 0.11.1 → 0.13.0

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.
@@ -8,11 +8,14 @@ import { snapshotProjectVersion } from "./migrations.js";
8
8
  import { getDefaultAnswers, scaffoldProject } from "./scaffold.js";
9
9
  import { SHARED_WORKSPACE_TEMPLATE_ROOT, } from "./template-registry.js";
10
10
  import { copyInterpolatedDirectory } from "./template-render.js";
11
- import { toKebabCase, toSnakeCase, } from "./string-case.js";
11
+ import { toKebabCase, toTitleCase, toSnakeCase, } from "./string-case.js";
12
+ import { appendWorkspaceInventoryEntries, getWorkspaceBlockSelectOptions, readWorkspaceInventory, } from "./workspace-inventory.js";
13
+ import { HOOKED_BLOCK_ANCHOR_PATTERN, HOOKED_BLOCK_POSITION_IDS, } from "./hooked-blocks.js";
14
+ import { resolveWorkspaceProject, WORKSPACE_TEMPLATE_PACKAGE, } from "./workspace-project.js";
12
15
  /**
13
16
  * Supported top-level `wp-typia add` kinds exposed by the canonical CLI.
14
17
  */
15
- export const ADD_KIND_IDS = ["block", "variation", "pattern"];
18
+ export const ADD_KIND_IDS = ["block", "variation", "pattern", "binding-source", "hooked-block"];
16
19
  /**
17
20
  * Supported built-in block families accepted by `wp-typia add block --template`.
18
21
  */
@@ -22,26 +25,37 @@ export const ADD_BLOCK_TEMPLATE_IDS = [
22
25
  "persistence",
23
26
  "compound",
24
27
  ];
25
- const WORKSPACE_TEMPLATE_PACKAGE = "@wp-typia/create-workspace-template";
26
- const BLOCK_CONFIG_ENTRY_MARKER = "\t// wp-typia add block entries";
27
28
  const COLLECTION_IMPORT_LINE = "import '../../collection';";
28
- const EMPTY_BLOCKS_ARRAY = `${BLOCK_CONFIG_ENTRY_MARKER}\n];`;
29
29
  const REST_MANIFEST_IMPORT_PATTERN = /import\s*\{[^}]*\bdefineEndpointManifest\b[^}]*\}\s*from\s*["']@wp-typia\/block-runtime\/metadata-core["'];?/m;
30
- function parsePackageManagerId(packageManagerField) {
31
- const packageManagerId = packageManagerField?.split("@", 1)[0];
32
- switch (packageManagerId) {
33
- case "bun":
34
- case "npm":
35
- case "pnpm":
36
- case "yarn":
37
- return packageManagerId;
38
- default:
39
- return "bun";
40
- }
41
- }
30
+ const VARIATIONS_IMPORT_LINE = "import { registerWorkspaceVariations } from './variations';";
31
+ const VARIATIONS_CALL_LINE = "registerWorkspaceVariations();";
32
+ const PATTERN_BOOTSTRAP_CATEGORY = "register_block_pattern_category";
33
+ const BINDING_SOURCE_SERVER_GLOB = "/src/bindings/*/server.php";
34
+ const BINDING_SOURCE_EDITOR_SCRIPT = "build/bindings/index.js";
35
+ const BINDING_SOURCE_EDITOR_ASSET = "build/bindings/index.asset.php";
36
+ const WORKSPACE_GENERATED_SLUG_PATTERN = /^[a-z][a-z0-9-]*$/;
42
37
  function normalizeBlockSlug(input) {
43
38
  return toKebabCase(input);
44
39
  }
40
+ function assertValidGeneratedSlug(label, slug, usage) {
41
+ if (!slug) {
42
+ throw new Error(`${label} is required. Use \`${usage}\`.`);
43
+ }
44
+ if (!WORKSPACE_GENERATED_SLUG_PATTERN.test(slug)) {
45
+ throw new Error(`${label} must start with a letter and contain only lowercase letters, numbers, and hyphens.`);
46
+ }
47
+ return slug;
48
+ }
49
+ function assertValidHookedBlockPosition(position) {
50
+ if (HOOKED_BLOCK_POSITION_IDS.includes(position)) {
51
+ return position;
52
+ }
53
+ throw new Error(`Hook position must be one of: ${HOOKED_BLOCK_POSITION_IDS.join(", ")}.`);
54
+ }
55
+ function getWorkspaceBootstrapPath(workspace) {
56
+ const workspaceBaseName = workspace.packageName.split("/").pop() ?? workspace.packageName;
57
+ return path.join(workspace.projectDir, `${workspaceBaseName}.php`);
58
+ }
45
59
  function buildWorkspacePhpPrefix(workspacePhpPrefix, slug) {
46
60
  return toSnakeCase(`${workspacePhpPrefix}_${slug}`);
47
61
  }
@@ -263,6 +277,357 @@ async function addCollectionImportsForTemplate(projectDir, templateId, variables
263
277
  }
264
278
  await ensureCollectionImport(path.join(projectDir, "src", "blocks", variables.slugKebabCase, "index.tsx"));
265
279
  }
280
+ function buildVariationConfigEntry(blockSlug, variationSlug) {
281
+ return [
282
+ "\t{",
283
+ `\t\tblock: ${quoteTsString(blockSlug)},`,
284
+ `\t\tfile: ${quoteTsString(`src/blocks/${blockSlug}/variations/${variationSlug}.ts`)},`,
285
+ `\t\tslug: ${quoteTsString(variationSlug)},`,
286
+ "\t},",
287
+ ].join("\n");
288
+ }
289
+ function buildPatternConfigEntry(patternSlug) {
290
+ return [
291
+ "\t{",
292
+ `\t\tfile: ${quoteTsString(`src/patterns/${patternSlug}.php`)},`,
293
+ `\t\tslug: ${quoteTsString(patternSlug)},`,
294
+ "\t},",
295
+ ].join("\n");
296
+ }
297
+ function buildBindingSourceConfigEntry(bindingSourceSlug) {
298
+ return [
299
+ "\t{",
300
+ `\t\teditorFile: ${quoteTsString(`src/bindings/${bindingSourceSlug}/editor.ts`)},`,
301
+ `\t\tserverFile: ${quoteTsString(`src/bindings/${bindingSourceSlug}/server.php`)},`,
302
+ `\t\tslug: ${quoteTsString(bindingSourceSlug)},`,
303
+ "\t},",
304
+ ].join("\n");
305
+ }
306
+ function buildVariationConstName(variationSlug) {
307
+ const identifierSegments = toKebabCase(variationSlug)
308
+ .split("-")
309
+ .filter(Boolean);
310
+ return `workspaceVariation_${identifierSegments.join("_")}`;
311
+ }
312
+ function getVariationConstBindings(variationSlugs) {
313
+ const seenConstNames = new Map();
314
+ return variationSlugs.map((variationSlug) => {
315
+ const constName = buildVariationConstName(variationSlug);
316
+ const previousSlug = seenConstNames.get(constName);
317
+ if (previousSlug && previousSlug !== variationSlug) {
318
+ throw new Error(`Variation slugs "${previousSlug}" and "${variationSlug}" generate the same registry identifier "${constName}". Rename one of the variations.`);
319
+ }
320
+ seenConstNames.set(constName, variationSlug);
321
+ return { constName, variationSlug };
322
+ });
323
+ }
324
+ function buildVariationSource(variationSlug, textDomain) {
325
+ const variationTitle = toTitleCase(variationSlug);
326
+ const variationConstName = buildVariationConstName(variationSlug);
327
+ return `import type { BlockVariation } from '@wordpress/blocks';
328
+ import { __ } from '@wordpress/i18n';
329
+
330
+ export const ${variationConstName} = {
331
+ \tname: ${quoteTsString(variationSlug)},
332
+ \ttitle: __( ${quoteTsString(variationTitle)}, ${quoteTsString(textDomain)} ),
333
+ \tdescription: __(
334
+ \t\t${quoteTsString(`A starter variation for ${variationTitle}.`)},
335
+ \t\t${quoteTsString(textDomain)},
336
+ \t),
337
+ \tattributes: {},
338
+ \tscope: ['inserter'],
339
+ } satisfies BlockVariation;
340
+ `;
341
+ }
342
+ function buildVariationIndexSource(variationSlugs) {
343
+ const variationBindings = getVariationConstBindings(variationSlugs);
344
+ const importLines = variationBindings
345
+ .map(({ constName, variationSlug }) => {
346
+ return `import { ${constName} } from './${variationSlug}';`;
347
+ })
348
+ .join("\n");
349
+ const variationConstNames = variationBindings
350
+ .map(({ constName }) => constName)
351
+ .join(",\n\t\t");
352
+ return `import { registerBlockVariation } from '@wordpress/blocks';
353
+ import metadata from '../block.json';
354
+ ${importLines ? `\n${importLines}` : ""}
355
+
356
+ const WORKSPACE_VARIATIONS = [
357
+ \t${variationConstNames}
358
+ \t// wp-typia add variation entries
359
+ ];
360
+
361
+ export function registerWorkspaceVariations() {
362
+ \tfor (const variation of WORKSPACE_VARIATIONS) {
363
+ \t\tregisterBlockVariation(metadata.name, variation);
364
+ \t}
365
+ }
366
+ `;
367
+ }
368
+ function buildPatternSource(patternSlug, namespace, textDomain) {
369
+ const patternTitle = toTitleCase(patternSlug);
370
+ return `<?php
371
+ if ( ! defined( 'ABSPATH' ) ) {
372
+ \treturn;
373
+ }
374
+
375
+ register_block_pattern(
376
+ \t'${namespace}/${patternSlug}',
377
+ \tarray(
378
+ \t\t'title' => __( ${JSON.stringify(patternTitle)}, '${textDomain}' ),
379
+ \t\t'description' => __( ${JSON.stringify(`A starter pattern for ${patternTitle}.`)}, '${textDomain}' ),
380
+ \t\t'categories' => array( '${namespace}' ),
381
+ \t\t'content' => '<!-- wp:paragraph --><p>' . esc_html__( 'Describe this pattern here.', '${textDomain}' ) . '</p><!-- /wp:paragraph -->',
382
+ \t)
383
+ );
384
+ `;
385
+ }
386
+ function buildBindingSourceServerSource(bindingSourceSlug, namespace, textDomain) {
387
+ const bindingSourceTitle = toTitleCase(bindingSourceSlug);
388
+ return `<?php
389
+ if ( ! defined( 'ABSPATH' ) ) {
390
+ \treturn;
391
+ }
392
+
393
+ if ( ! function_exists( 'register_block_bindings_source' ) ) {
394
+ \treturn;
395
+ }
396
+
397
+ register_block_bindings_source(
398
+ \t'${namespace}/${bindingSourceSlug}',
399
+ \tarray(
400
+ \t\t'label' => __( ${JSON.stringify(bindingSourceTitle)}, '${textDomain}' ),
401
+ \t\t'get_value_callback' => static function( array $source_args ) : string {
402
+ \t\t\t$field = isset( $source_args['field'] ) && is_string( $source_args['field'] )
403
+ \t\t\t\t? $source_args['field']
404
+ \t\t\t\t: '${bindingSourceSlug}';
405
+
406
+ \t\t\treturn sprintf(
407
+ \t\t\t\t__( 'Replace %s with real binding source data.', '${textDomain}' ),
408
+ \t\t\t\t$field
409
+ \t\t\t);
410
+ \t\t},
411
+ \t)
412
+ );
413
+ `;
414
+ }
415
+ function buildBindingSourceEditorSource(bindingSourceSlug, namespace, textDomain) {
416
+ const bindingSourceTitle = toTitleCase(bindingSourceSlug);
417
+ return `import { registerBlockBindingsSource } from '@wordpress/blocks';
418
+ import { __ } from '@wordpress/i18n';
419
+
420
+ registerBlockBindingsSource( {
421
+ \tname: ${quoteTsString(`${namespace}/${bindingSourceSlug}`)},
422
+ \tlabel: __( ${quoteTsString(bindingSourceTitle)}, ${quoteTsString(textDomain)} ),
423
+ \tgetFieldsList() {
424
+ \t\treturn [
425
+ \t\t\t{
426
+ \t\t\t\tlabel: __( ${quoteTsString(bindingSourceTitle)}, ${quoteTsString(textDomain)} ),
427
+ \t\t\t\ttype: 'string',
428
+ \t\t\t\targs: {
429
+ \t\t\t\t\tfield: ${quoteTsString(bindingSourceSlug)},
430
+ \t\t\t\t},
431
+ \t\t\t},
432
+ \t\t];
433
+ \t},
434
+ \tgetValues( { bindings } ) {
435
+ \t\tconst values: Record<string, string> = {};
436
+ \t\tfor ( const attributeName of Object.keys( bindings ) ) {
437
+ \t\t\tvalues[ attributeName ] = ${quoteTsString(`TODO: replace ${bindingSourceSlug} with real editor-side values.`)};
438
+ \t\t}
439
+ \t\treturn values;
440
+ \t},
441
+ } );
442
+ `;
443
+ }
444
+ function buildBindingSourceIndexSource(bindingSourceSlugs) {
445
+ const importLines = bindingSourceSlugs
446
+ .map((bindingSourceSlug) => `import './${bindingSourceSlug}/editor';`)
447
+ .join("\n");
448
+ return `${importLines}${importLines ? "\n\n" : ""}// wp-typia add binding-source entries\n`;
449
+ }
450
+ async function ensureVariationRegistrationHook(blockIndexPath) {
451
+ await patchFile(blockIndexPath, (source) => {
452
+ let nextSource = source;
453
+ if (!nextSource.includes(VARIATIONS_IMPORT_LINE)) {
454
+ nextSource = `${VARIATIONS_IMPORT_LINE}\n${nextSource}`;
455
+ }
456
+ if (!nextSource.includes(VARIATIONS_CALL_LINE)) {
457
+ const callInsertionPatterns = [
458
+ /(registerBlockType<[\s\S]*?\);\s*)/u,
459
+ /(registerBlockType\([\s\S]*?\);\s*)/u,
460
+ ];
461
+ let inserted = false;
462
+ for (const pattern of callInsertionPatterns) {
463
+ const candidate = nextSource.replace(pattern, (match) => `${match}\n${VARIATIONS_CALL_LINE}\n`);
464
+ if (candidate !== nextSource) {
465
+ nextSource = candidate;
466
+ inserted = true;
467
+ break;
468
+ }
469
+ }
470
+ if (!inserted) {
471
+ nextSource = `${nextSource.trimEnd()}\n\n${VARIATIONS_CALL_LINE}\n`;
472
+ }
473
+ }
474
+ if (!nextSource.includes(VARIATIONS_CALL_LINE)) {
475
+ throw new Error(`Unable to inject ${VARIATIONS_CALL_LINE} into ${path.basename(blockIndexPath)}.`);
476
+ }
477
+ return nextSource;
478
+ });
479
+ }
480
+ async function writeVariationRegistry(projectDir, blockSlug, variationSlug) {
481
+ const variationsDir = path.join(projectDir, "src", "blocks", blockSlug, "variations");
482
+ const variationsIndexPath = path.join(variationsDir, "index.ts");
483
+ await fsp.mkdir(variationsDir, { recursive: true });
484
+ const existingVariationSlugs = fs.existsSync(variationsDir)
485
+ ? fs
486
+ .readdirSync(variationsDir)
487
+ .filter((entry) => entry.endsWith(".ts") && entry !== "index.ts")
488
+ .map((entry) => entry.replace(/\.ts$/u, ""))
489
+ : [];
490
+ const nextVariationSlugs = Array.from(new Set([...existingVariationSlugs, variationSlug])).sort();
491
+ await fsp.writeFile(variationsIndexPath, buildVariationIndexSource(nextVariationSlugs), "utf8");
492
+ }
493
+ async function ensurePatternBootstrapAnchors(workspace) {
494
+ const workspaceBaseName = workspace.packageName.split("/").pop() ?? workspace.packageName;
495
+ const bootstrapPath = getWorkspaceBootstrapPath(workspace);
496
+ await patchFile(bootstrapPath, (source) => {
497
+ let nextSource = source;
498
+ const patternCategoryFunctionName = `${workspace.workspace.phpPrefix}_register_pattern_category`;
499
+ const patternRegistrationFunctionName = `${workspace.workspace.phpPrefix}_register_patterns`;
500
+ const patternCategoryHook = `add_action( 'init', '${patternCategoryFunctionName}' );`;
501
+ const patternRegistrationHook = `add_action( 'init', '${patternRegistrationFunctionName}', 20 );`;
502
+ const patternFunctions = `
503
+
504
+ function ${patternCategoryFunctionName}() {
505
+ \tif ( function_exists( 'register_block_pattern_category' ) ) {
506
+ \t\tregister_block_pattern_category(
507
+ \t\t\t'${workspace.workspace.namespace}',
508
+ \t\t\tarray(
509
+ \t\t\t\t'label' => __( ${JSON.stringify(`${toTitleCase(workspaceBaseName)} Patterns`)}, '${workspace.workspace.textDomain}' ),
510
+ \t\t\t)
511
+ \t\t);
512
+ \t}
513
+ }
514
+
515
+ function ${patternRegistrationFunctionName}() {
516
+ \tforeach ( glob( __DIR__ . '/src/patterns/*.php' ) ?: array() as $pattern_module ) {
517
+ \t\trequire $pattern_module;
518
+ \t}
519
+ }
520
+ `;
521
+ if (!nextSource.includes(PATTERN_BOOTSTRAP_CATEGORY)) {
522
+ const insertionAnchors = [
523
+ /add_action\(\s*["']init["']\s*,\s*["'][^"']+_load_textdomain["']\s*\);\s*\n/u,
524
+ /\?>\s*$/u,
525
+ ];
526
+ let inserted = false;
527
+ for (const anchor of insertionAnchors) {
528
+ const candidate = nextSource.replace(anchor, (match) => `${patternFunctions}\n${match}`);
529
+ if (candidate !== nextSource) {
530
+ nextSource = candidate;
531
+ inserted = true;
532
+ break;
533
+ }
534
+ }
535
+ if (!inserted) {
536
+ nextSource = `${nextSource.trimEnd()}\n${patternFunctions}\n`;
537
+ }
538
+ }
539
+ if (!nextSource.includes(patternCategoryFunctionName) ||
540
+ !nextSource.includes(patternRegistrationFunctionName)) {
541
+ throw new Error(`Unable to inject pattern bootstrap functions into ${path.basename(bootstrapPath)}.`);
542
+ }
543
+ if (!nextSource.includes(patternCategoryHook)) {
544
+ nextSource = `${nextSource.trimEnd()}\n${patternCategoryHook}\n`;
545
+ }
546
+ if (!nextSource.includes(patternRegistrationHook)) {
547
+ nextSource = `${nextSource.trimEnd()}\n${patternRegistrationHook}\n`;
548
+ }
549
+ return nextSource;
550
+ });
551
+ }
552
+ async function ensureBindingSourceBootstrapAnchors(workspace) {
553
+ const bootstrapPath = getWorkspaceBootstrapPath(workspace);
554
+ await patchFile(bootstrapPath, (source) => {
555
+ let nextSource = source;
556
+ const workspaceBaseName = workspace.packageName.split("/").pop() ?? workspace.packageName;
557
+ const bindingRegistrationFunctionName = `${workspace.workspace.phpPrefix}_register_binding_sources`;
558
+ const bindingEditorEnqueueFunctionName = `${workspace.workspace.phpPrefix}_enqueue_binding_sources_editor`;
559
+ const bindingRegistrationHook = `add_action( 'init', '${bindingRegistrationFunctionName}', 20 );`;
560
+ const bindingEditorEnqueueHook = `add_action( 'enqueue_block_editor_assets', '${bindingEditorEnqueueFunctionName}' );`;
561
+ const bindingRegistrationFunction = `
562
+
563
+ function ${bindingRegistrationFunctionName}() {
564
+ \tforeach ( glob( __DIR__ . '${BINDING_SOURCE_SERVER_GLOB}' ) ?: array() as $binding_source_module ) {
565
+ \t\trequire_once $binding_source_module;
566
+ \t}
567
+ }
568
+ `;
569
+ const bindingEditorEnqueueFunction = `
570
+
571
+ function ${bindingEditorEnqueueFunctionName}() {
572
+ \t$script_path = __DIR__ . '/${BINDING_SOURCE_EDITOR_SCRIPT}';
573
+ \t$asset_path = __DIR__ . '/${BINDING_SOURCE_EDITOR_ASSET}';
574
+
575
+ \tif ( ! file_exists( $script_path ) || ! file_exists( $asset_path ) ) {
576
+ \t\treturn;
577
+ \t}
578
+
579
+ \t$asset = require $asset_path;
580
+ \tif ( ! is_array( $asset ) ) {
581
+ \t\t$asset = array();
582
+ \t}
583
+
584
+ \twp_enqueue_script(
585
+ \t\t'${workspaceBaseName}-binding-sources',
586
+ \t\tplugins_url( '${BINDING_SOURCE_EDITOR_SCRIPT}', __FILE__ ),
587
+ \t\tisset( $asset['dependencies'] ) && is_array( $asset['dependencies'] ) ? $asset['dependencies'] : array(),
588
+ \t\tisset( $asset['version'] ) ? $asset['version'] : filemtime( $script_path ),
589
+ \t\ttrue
590
+ \t);
591
+ }
592
+ `;
593
+ const insertionAnchors = [
594
+ /add_action\(\s*["']init["']\s*,\s*["'][^"']+_load_textdomain["']\s*\);\s*\n/u,
595
+ /\?>\s*$/u,
596
+ ];
597
+ const hasPhpFunctionDefinition = (functionName) => new RegExp(`function\\s+${functionName}\\s*\\(`, "u").test(nextSource);
598
+ const insertPhpSnippet = (snippet) => {
599
+ for (const anchor of insertionAnchors) {
600
+ const candidate = nextSource.replace(anchor, (match) => `${snippet}\n${match}`);
601
+ if (candidate !== nextSource) {
602
+ nextSource = candidate;
603
+ return;
604
+ }
605
+ }
606
+ nextSource = `${nextSource.trimEnd()}\n${snippet}\n`;
607
+ };
608
+ const appendPhpSnippet = (snippet) => {
609
+ const closingTagPattern = /\?>\s*$/u;
610
+ if (closingTagPattern.test(nextSource)) {
611
+ nextSource = nextSource.replace(closingTagPattern, `${snippet}\n?>`);
612
+ return;
613
+ }
614
+ nextSource = `${nextSource.trimEnd()}\n${snippet}\n`;
615
+ };
616
+ if (!hasPhpFunctionDefinition(bindingRegistrationFunctionName)) {
617
+ insertPhpSnippet(bindingRegistrationFunction);
618
+ }
619
+ if (!hasPhpFunctionDefinition(bindingEditorEnqueueFunctionName)) {
620
+ insertPhpSnippet(bindingEditorEnqueueFunction);
621
+ }
622
+ if (!nextSource.includes(bindingRegistrationHook)) {
623
+ appendPhpSnippet(bindingRegistrationHook);
624
+ }
625
+ if (!nextSource.includes(bindingEditorEnqueueHook)) {
626
+ appendPhpSnippet(bindingEditorEnqueueHook);
627
+ }
628
+ return nextSource;
629
+ });
630
+ }
266
631
  function ensureBlockConfigCanAddRestManifests(source) {
267
632
  const importLine = "import { defineEndpointManifest } from '@wp-typia/block-runtime/metadata-core';";
268
633
  if (REST_MANIFEST_IMPORT_PATTERN.test(source)) {
@@ -271,21 +636,35 @@ function ensureBlockConfigCanAddRestManifests(source) {
271
636
  return `${importLine}\n\n${source}`;
272
637
  }
273
638
  async function appendBlockConfigEntries(projectDir, entries, needsRestManifestImport) {
274
- const blockConfigPath = path.join(projectDir, "scripts", "block-config.ts");
275
- await patchFile(blockConfigPath, (source) => {
276
- let nextSource = source;
277
- if (needsRestManifestImport) {
278
- nextSource = ensureBlockConfigCanAddRestManifests(nextSource);
279
- }
280
- if (nextSource.includes(BLOCK_CONFIG_ENTRY_MARKER)) {
281
- return nextSource.replace(BLOCK_CONFIG_ENTRY_MARKER, `${entries.join("\n")}\n${BLOCK_CONFIG_ENTRY_MARKER}`);
282
- }
283
- if (nextSource.includes(EMPTY_BLOCKS_ARRAY)) {
284
- return nextSource.replace(EMPTY_BLOCKS_ARRAY, `${entries.join("\n")}\n];`);
285
- }
286
- return nextSource.replace("];", `${entries.join("\n")}\n];`);
639
+ await appendWorkspaceInventoryEntries(projectDir, {
640
+ blockEntries: entries,
641
+ transformSource: needsRestManifestImport ? ensureBlockConfigCanAddRestManifests : undefined,
287
642
  });
288
643
  }
644
+ async function writeBindingSourceRegistry(projectDir, bindingSourceSlug) {
645
+ const bindingsDir = path.join(projectDir, "src", "bindings");
646
+ const bindingsIndexPath = resolveBindingSourceRegistryPath(projectDir);
647
+ await fsp.mkdir(bindingsDir, { recursive: true });
648
+ const existingBindingSourceSlugs = fs.existsSync(bindingsDir)
649
+ ? fs
650
+ .readdirSync(bindingsDir, { withFileTypes: true })
651
+ .filter((entry) => entry.isDirectory())
652
+ .map((entry) => entry.name)
653
+ : [];
654
+ const nextBindingSourceSlugs = Array.from(new Set([...existingBindingSourceSlugs, bindingSourceSlug])).sort();
655
+ await fsp.writeFile(bindingsIndexPath, buildBindingSourceIndexSource(nextBindingSourceSlugs), "utf8");
656
+ }
657
+ function resolveBindingSourceRegistryPath(projectDir) {
658
+ const bindingsDir = path.join(projectDir, "src", "bindings");
659
+ return [path.join(bindingsDir, "index.ts"), path.join(bindingsDir, "index.js")].find((candidatePath) => fs.existsSync(candidatePath)) ?? path.join(bindingsDir, "index.ts");
660
+ }
661
+ async function snapshotWorkspaceFiles(filePaths) {
662
+ const uniquePaths = Array.from(new Set(filePaths));
663
+ return Promise.all(uniquePaths.map(async (filePath) => ({
664
+ filePath,
665
+ source: await readOptionalFile(filePath),
666
+ })));
667
+ }
289
668
  async function renderWorkspacePersistenceServerModule(projectDir, variables) {
290
669
  const targetDir = path.join(projectDir, "src", "blocks", variables.slugKebabCase);
291
670
  const templateDir = buildServerTemplateRoot(variables.persistencePolicy);
@@ -387,39 +766,6 @@ async function syncWorkspaceAddedBlockArtifacts(projectDir, templateId, variable
387
766
  await syncWorkspacePersistenceArtifacts(projectDir, variables);
388
767
  }
389
768
  }
390
- function resolveWorkspaceProject(startDir) {
391
- let currentDir = path.resolve(startDir);
392
- while (true) {
393
- const packageJsonPath = path.join(currentDir, "package.json");
394
- if (fs.existsSync(packageJsonPath)) {
395
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
396
- if (packageJson.wpTypia?.projectType === "workspace" &&
397
- packageJson.wpTypia?.templatePackage === WORKSPACE_TEMPLATE_PACKAGE &&
398
- typeof packageJson.wpTypia.namespace === "string" &&
399
- typeof packageJson.wpTypia.textDomain === "string" &&
400
- typeof packageJson.wpTypia.phpPrefix === "string") {
401
- return {
402
- author: typeof packageJson.author === "string" ? packageJson.author : "Your Name",
403
- packageManager: parsePackageManagerId(packageJson.packageManager),
404
- projectDir: currentDir,
405
- workspace: {
406
- namespace: packageJson.wpTypia.namespace,
407
- phpPrefix: packageJson.wpTypia.phpPrefix,
408
- projectType: "workspace",
409
- templatePackage: WORKSPACE_TEMPLATE_PACKAGE,
410
- textDomain: packageJson.wpTypia.textDomain,
411
- },
412
- };
413
- }
414
- }
415
- const parentDir = path.dirname(currentDir);
416
- if (parentDir === currentDir) {
417
- break;
418
- }
419
- currentDir = parentDir;
420
- }
421
- throw new Error(`This command must run inside a ${WORKSPACE_TEMPLATE_PACKAGE} project. Create one with \`wp-typia create my-plugin --template ${WORKSPACE_TEMPLATE_PACKAGE}\` first.`);
422
- }
423
769
  function assertPersistenceFlagsAllowed(templateId, options) {
424
770
  const hasPersistenceFlags = typeof options.dataStorageMode === "string" ||
425
771
  typeof options.persistencePolicy === "string";
@@ -447,12 +793,17 @@ function assertPersistenceFlagsAllowed(templateId, options) {
447
793
  export function formatAddHelpText() {
448
794
  return `Usage:
449
795
  wp-typia add block <name> --template <${ADD_BLOCK_TEMPLATE_IDS.join("|")}> [--data-storage <post-meta|custom-table>] [--persistence-policy <authenticated|public>]
450
- wp-typia add variation
451
- wp-typia add pattern
796
+ wp-typia add variation <name> --block <block-slug>
797
+ wp-typia add pattern <name>
798
+ wp-typia add binding-source <name>
799
+ wp-typia add hooked-block <block-slug> --anchor <anchor-block-name> --position <${HOOKED_BLOCK_POSITION_IDS.join("|")}>
452
800
 
453
801
  Notes:
454
- \`wp-typia add block\` runs only inside official ${WORKSPACE_TEMPLATE_PACKAGE} workspaces.
455
- \`wp-typia add variation\` and \`wp-typia add pattern\` are reserved placeholders for follow-up workflows.`;
802
+ \`wp-typia add\` runs only inside official ${WORKSPACE_TEMPLATE_PACKAGE} workspaces.
803
+ \`add variation\` targets an existing block slug from \`scripts/block-config.ts\`.
804
+ \`add pattern\` scaffolds a namespaced PHP pattern shell under \`src/patterns/\`.
805
+ \`add binding-source\` scaffolds shared PHP and editor registration under \`src/bindings/\`.
806
+ \`add hooked-block\` patches an existing workspace block's \`block.json\` \`blockHooks\` metadata.`;
456
807
  }
457
808
  /**
458
809
  * Seeds an empty official workspace migration project before any blocks are added.
@@ -467,15 +818,16 @@ export async function seedWorkspaceMigrationProject(projectDir, currentMigration
467
818
  ensureMigrationDirectories(projectDir, []);
468
819
  writeInitialMigrationScaffold(projectDir, currentMigrationVersion, []);
469
820
  }
470
- async function rollbackWorkspaceMutation(projectDir, snapshot) {
821
+ async function rollbackWorkspaceMutation(snapshot) {
471
822
  for (const targetPath of snapshot.targetPaths) {
472
823
  await fsp.rm(targetPath, { force: true, recursive: true });
473
824
  }
474
825
  for (const snapshotDir of snapshot.snapshotDirs) {
475
826
  await fsp.rm(snapshotDir, { force: true, recursive: true });
476
827
  }
477
- await restoreOptionalFile(path.join(projectDir, "scripts", "block-config.ts"), snapshot.blockConfigSource);
478
- await restoreOptionalFile(path.join(projectDir, "src", "migrations", "config.ts"), snapshot.migrationConfigSource);
828
+ for (const { filePath, source } of snapshot.fileSources) {
829
+ await restoreOptionalFile(filePath, source);
830
+ }
479
831
  }
480
832
  /**
481
833
  * Adds one built-in block slice to an official workspace project.
@@ -496,9 +848,10 @@ export async function runAddBlockCommand({ blockName, cwd = process.cwd(), dataS
496
848
  try {
497
849
  tempRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "wp-typia-add-block-"));
498
850
  const tempProjectDir = path.join(tempRoot, normalizedSlug);
851
+ const blockConfigPath = path.join(workspace.projectDir, "scripts", "block-config.ts");
852
+ const migrationConfigPath = path.join(workspace.projectDir, "src", "migrations", "config.ts");
499
853
  const blockPhpPrefix = buildWorkspacePhpPrefix(workspace.workspace.phpPrefix, normalizedSlug);
500
- const blockConfigSource = await readOptionalFile(path.join(workspace.projectDir, "scripts", "block-config.ts"));
501
- const migrationConfigSource = await readOptionalFile(path.join(workspace.projectDir, "src", "migrations", "config.ts"));
854
+ const migrationConfigSource = await readOptionalFile(migrationConfigPath);
502
855
  const migrationConfig = migrationConfigSource === null ? null : parseMigrationConfig(migrationConfigSource);
503
856
  const result = await scaffoldProject({
504
857
  answers: {
@@ -520,8 +873,7 @@ export async function runAddBlockCommand({ blockName, cwd = process.cwd(), dataS
520
873
  });
521
874
  assertBlockTargetsDoNotExist(workspace.projectDir, resolvedTemplateId, result.variables);
522
875
  const mutationSnapshot = {
523
- blockConfigSource,
524
- migrationConfigSource,
876
+ fileSources: await snapshotWorkspaceFiles([blockConfigPath, migrationConfigPath]),
525
877
  snapshotDirs: migrationConfig === null
526
878
  ? []
527
879
  : buildMigrationBlocks(resolvedTemplateId, result.variables).map((block) => path.join(workspace.projectDir, ...migrationConfig.snapshotDir.split("/"), migrationConfig.currentMigrationVersion, block.key)),
@@ -542,7 +894,7 @@ export async function runAddBlockCommand({ blockName, cwd = process.cwd(), dataS
542
894
  };
543
895
  }
544
896
  catch (error) {
545
- await rollbackWorkspaceMutation(workspace.projectDir, mutationSnapshot);
897
+ await rollbackWorkspaceMutation(mutationSnapshot);
546
898
  throw error;
547
899
  }
548
900
  }
@@ -552,10 +904,284 @@ export async function runAddBlockCommand({ blockName, cwd = process.cwd(), dataS
552
904
  }
553
905
  }
554
906
  }
907
+ function resolveWorkspaceBlock(inventory, blockSlug) {
908
+ const block = inventory.blocks.find((entry) => entry.slug === blockSlug);
909
+ if (!block) {
910
+ throw new Error(`Unknown workspace block "${blockSlug}". Choose one of: ${inventory.blocks.map((entry) => entry.slug).join(", ")}`);
911
+ }
912
+ return block;
913
+ }
914
+ function assertValidHookAnchor(anchorBlockName) {
915
+ const trimmed = anchorBlockName.trim();
916
+ if (!trimmed) {
917
+ throw new Error("`wp-typia add hooked-block` requires --anchor <anchor-block-name>.");
918
+ }
919
+ if (!HOOKED_BLOCK_ANCHOR_PATTERN.test(trimmed)) {
920
+ throw new Error("`wp-typia add hooked-block` requires --anchor <anchor-block-name> to use the full `namespace/slug` block name format.");
921
+ }
922
+ return trimmed;
923
+ }
924
+ function readWorkspaceBlockJson(projectDir, blockSlug) {
925
+ const blockJsonPath = path.join(projectDir, "src", "blocks", blockSlug, "block.json");
926
+ if (!fs.existsSync(blockJsonPath)) {
927
+ throw new Error(`Missing ${path.relative(projectDir, blockJsonPath)} for workspace block "${blockSlug}".`);
928
+ }
929
+ let blockJson;
930
+ try {
931
+ blockJson = JSON.parse(fs.readFileSync(blockJsonPath, "utf8"));
932
+ }
933
+ catch (error) {
934
+ throw new Error(error instanceof Error
935
+ ? `Failed to parse ${path.relative(projectDir, blockJsonPath)}: ${error.message}`
936
+ : `Failed to parse ${path.relative(projectDir, blockJsonPath)}.`);
937
+ }
938
+ if (!blockJson || typeof blockJson !== "object" || Array.isArray(blockJson)) {
939
+ throw new Error(`${path.relative(projectDir, blockJsonPath)} must contain a JSON object.`);
940
+ }
941
+ return {
942
+ blockJson: blockJson,
943
+ blockJsonPath,
944
+ };
945
+ }
946
+ function getMutableBlockHooks(blockJson, blockJsonRelativePath) {
947
+ const blockHooks = blockJson.blockHooks;
948
+ if (blockHooks === undefined) {
949
+ const nextHooks = {};
950
+ blockJson.blockHooks = nextHooks;
951
+ return nextHooks;
952
+ }
953
+ if (!blockHooks || typeof blockHooks !== "object" || Array.isArray(blockHooks)) {
954
+ throw new Error(`${blockJsonRelativePath} must define blockHooks as an object when present.`);
955
+ }
956
+ return blockHooks;
957
+ }
958
+ function assertVariationDoesNotExist(projectDir, blockSlug, variationSlug, inventory) {
959
+ const variationPath = path.join(projectDir, "src", "blocks", blockSlug, "variations", `${variationSlug}.ts`);
960
+ if (fs.existsSync(variationPath)) {
961
+ throw new Error(`A variation already exists at ${path.relative(projectDir, variationPath)}. Choose a different name.`);
962
+ }
963
+ if (inventory.variations.some((entry) => entry.block === blockSlug && entry.slug === variationSlug)) {
964
+ throw new Error(`A variation inventory entry already exists for ${blockSlug}/${variationSlug}. Choose a different name.`);
965
+ }
966
+ }
967
+ function assertPatternDoesNotExist(projectDir, patternSlug, inventory) {
968
+ const patternPath = path.join(projectDir, "src", "patterns", `${patternSlug}.php`);
969
+ if (fs.existsSync(patternPath)) {
970
+ throw new Error(`A pattern already exists at ${path.relative(projectDir, patternPath)}. Choose a different name.`);
971
+ }
972
+ if (inventory.patterns.some((entry) => entry.slug === patternSlug)) {
973
+ throw new Error(`A pattern inventory entry already exists for ${patternSlug}. Choose a different name.`);
974
+ }
975
+ }
976
+ function assertBindingSourceDoesNotExist(projectDir, bindingSourceSlug, inventory) {
977
+ const bindingSourceDir = path.join(projectDir, "src", "bindings", bindingSourceSlug);
978
+ if (fs.existsSync(bindingSourceDir)) {
979
+ throw new Error(`A binding source already exists at ${path.relative(projectDir, bindingSourceDir)}. Choose a different name.`);
980
+ }
981
+ if (inventory.bindingSources.some((entry) => entry.slug === bindingSourceSlug)) {
982
+ throw new Error(`A binding source inventory entry already exists for ${bindingSourceSlug}. Choose a different name.`);
983
+ }
984
+ }
985
+ /**
986
+ * Add one variation entry to an existing workspace block.
987
+ *
988
+ * @param options Command options for the variation scaffold workflow.
989
+ * @param options.blockName Target workspace block slug that will own the variation.
990
+ * @param options.cwd Working directory used to resolve the nearest official workspace.
991
+ * Defaults to `process.cwd()`.
992
+ * @param options.variationName Human-entered variation name that will be normalized
993
+ * and validated before files are written.
994
+ * @returns A promise that resolves with the normalized `blockSlug`,
995
+ * `variationSlug`, and owning `projectDir` after the variation files and
996
+ * inventory entry have been written successfully.
997
+ * @throws {Error} When the command is run outside an official workspace, when
998
+ * the target block is unknown, when the variation slug is invalid, or when a
999
+ * conflicting file or inventory entry already exists.
1000
+ */
1001
+ export async function runAddVariationCommand({ blockName, cwd = process.cwd(), variationName, }) {
1002
+ const workspace = resolveWorkspaceProject(cwd);
1003
+ const blockSlug = normalizeBlockSlug(blockName);
1004
+ const variationSlug = assertValidGeneratedSlug("Variation name", normalizeBlockSlug(variationName), "wp-typia add variation <name> --block <block-slug>");
1005
+ const inventory = readWorkspaceInventory(workspace.projectDir);
1006
+ resolveWorkspaceBlock(inventory, blockSlug);
1007
+ assertVariationDoesNotExist(workspace.projectDir, blockSlug, variationSlug, inventory);
1008
+ const blockConfigPath = path.join(workspace.projectDir, "scripts", "block-config.ts");
1009
+ const blockIndexPath = path.join(workspace.projectDir, "src", "blocks", blockSlug, "index.tsx");
1010
+ const variationsDir = path.join(workspace.projectDir, "src", "blocks", blockSlug, "variations");
1011
+ const variationFilePath = path.join(variationsDir, `${variationSlug}.ts`);
1012
+ const variationsIndexPath = path.join(variationsDir, "index.ts");
1013
+ const mutationSnapshot = {
1014
+ fileSources: await snapshotWorkspaceFiles([
1015
+ blockConfigPath,
1016
+ blockIndexPath,
1017
+ variationsIndexPath,
1018
+ ]),
1019
+ snapshotDirs: [],
1020
+ targetPaths: [variationFilePath],
1021
+ };
1022
+ try {
1023
+ await fsp.mkdir(variationsDir, { recursive: true });
1024
+ await fsp.writeFile(variationFilePath, buildVariationSource(variationSlug, workspace.workspace.textDomain), "utf8");
1025
+ await writeVariationRegistry(workspace.projectDir, blockSlug, variationSlug);
1026
+ await ensureVariationRegistrationHook(blockIndexPath);
1027
+ await appendWorkspaceInventoryEntries(workspace.projectDir, {
1028
+ variationEntries: [buildVariationConfigEntry(blockSlug, variationSlug)],
1029
+ });
1030
+ return {
1031
+ blockSlug,
1032
+ projectDir: workspace.projectDir,
1033
+ variationSlug,
1034
+ };
1035
+ }
1036
+ catch (error) {
1037
+ await rollbackWorkspaceMutation(mutationSnapshot);
1038
+ throw error;
1039
+ }
1040
+ }
555
1041
  /**
556
- * Returns the current placeholder guidance for unsupported `wp-typia add` kinds.
1042
+ * Add one PHP block pattern shell to an official workspace project.
1043
+ *
1044
+ * @param options Command options for the pattern scaffold workflow.
1045
+ * @param options.cwd Working directory used to resolve the nearest official workspace.
1046
+ * Defaults to `process.cwd()`.
1047
+ * @param options.patternName Human-entered pattern name that will be normalized
1048
+ * and validated before files are written.
1049
+ * @returns A promise that resolves with the normalized `patternSlug` and
1050
+ * owning `projectDir` after the pattern file and inventory entry have been
1051
+ * written successfully.
1052
+ * @throws {Error} When the command is run outside an official workspace, when
1053
+ * the pattern slug is invalid, or when a conflicting file or inventory entry
1054
+ * already exists.
557
1055
  */
558
- export function createAddPlaceholderMessage(kind) {
559
- const issueNumber = kind === "variation" ? "#157" : "#158";
560
- return `\`wp-typia add ${kind}\` is not implemented yet. Track ${issueNumber} for the first supported ${kind} workflow.`;
1056
+ export async function runAddPatternCommand({ cwd = process.cwd(), patternName, }) {
1057
+ const workspace = resolveWorkspaceProject(cwd);
1058
+ const patternSlug = assertValidGeneratedSlug("Pattern name", normalizeBlockSlug(patternName), "wp-typia add pattern <name>");
1059
+ const inventory = readWorkspaceInventory(workspace.projectDir);
1060
+ assertPatternDoesNotExist(workspace.projectDir, patternSlug, inventory);
1061
+ const blockConfigPath = path.join(workspace.projectDir, "scripts", "block-config.ts");
1062
+ const bootstrapPath = getWorkspaceBootstrapPath(workspace);
1063
+ const patternFilePath = path.join(workspace.projectDir, "src", "patterns", `${patternSlug}.php`);
1064
+ const mutationSnapshot = {
1065
+ fileSources: await snapshotWorkspaceFiles([blockConfigPath, bootstrapPath]),
1066
+ snapshotDirs: [],
1067
+ targetPaths: [patternFilePath],
1068
+ };
1069
+ try {
1070
+ await fsp.mkdir(path.dirname(patternFilePath), { recursive: true });
1071
+ await ensurePatternBootstrapAnchors(workspace);
1072
+ await fsp.writeFile(patternFilePath, buildPatternSource(patternSlug, workspace.workspace.namespace, workspace.workspace.textDomain), "utf8");
1073
+ await appendWorkspaceInventoryEntries(workspace.projectDir, {
1074
+ patternEntries: [buildPatternConfigEntry(patternSlug)],
1075
+ });
1076
+ return {
1077
+ patternSlug,
1078
+ projectDir: workspace.projectDir,
1079
+ };
1080
+ }
1081
+ catch (error) {
1082
+ await rollbackWorkspaceMutation(mutationSnapshot);
1083
+ throw error;
1084
+ }
1085
+ }
1086
+ /**
1087
+ * Add one block binding source scaffold to an official workspace project.
1088
+ *
1089
+ * @param options Command options for the binding-source scaffold workflow.
1090
+ * @param options.bindingSourceName Human-entered binding source name that will
1091
+ * be normalized and validated before files are written.
1092
+ * @param options.cwd Working directory used to resolve the nearest official
1093
+ * workspace. Defaults to `process.cwd()`.
1094
+ * @returns A promise that resolves with the normalized `bindingSourceSlug` and
1095
+ * owning `projectDir` after the server/editor files and inventory entry have
1096
+ * been written successfully.
1097
+ * @throws {Error} When the command is run outside an official workspace, when
1098
+ * the slug is invalid, or when a conflicting file or inventory entry exists.
1099
+ */
1100
+ export async function runAddBindingSourceCommand({ bindingSourceName, cwd = process.cwd(), }) {
1101
+ const workspace = resolveWorkspaceProject(cwd);
1102
+ const bindingSourceSlug = assertValidGeneratedSlug("Binding source name", normalizeBlockSlug(bindingSourceName), "wp-typia add binding-source <name>");
1103
+ const inventory = readWorkspaceInventory(workspace.projectDir);
1104
+ assertBindingSourceDoesNotExist(workspace.projectDir, bindingSourceSlug, inventory);
1105
+ const blockConfigPath = path.join(workspace.projectDir, "scripts", "block-config.ts");
1106
+ const bootstrapPath = getWorkspaceBootstrapPath(workspace);
1107
+ const bindingsIndexPath = resolveBindingSourceRegistryPath(workspace.projectDir);
1108
+ const bindingSourceDir = path.join(workspace.projectDir, "src", "bindings", bindingSourceSlug);
1109
+ const serverFilePath = path.join(bindingSourceDir, "server.php");
1110
+ const editorFilePath = path.join(bindingSourceDir, "editor.ts");
1111
+ const mutationSnapshot = {
1112
+ fileSources: await snapshotWorkspaceFiles([blockConfigPath, bootstrapPath, bindingsIndexPath]),
1113
+ snapshotDirs: [],
1114
+ targetPaths: [bindingSourceDir],
1115
+ };
1116
+ try {
1117
+ await fsp.mkdir(bindingSourceDir, { recursive: true });
1118
+ await ensureBindingSourceBootstrapAnchors(workspace);
1119
+ await fsp.writeFile(serverFilePath, buildBindingSourceServerSource(bindingSourceSlug, workspace.workspace.namespace, workspace.workspace.textDomain), "utf8");
1120
+ await fsp.writeFile(editorFilePath, buildBindingSourceEditorSource(bindingSourceSlug, workspace.workspace.namespace, workspace.workspace.textDomain), "utf8");
1121
+ await writeBindingSourceRegistry(workspace.projectDir, bindingSourceSlug);
1122
+ await appendWorkspaceInventoryEntries(workspace.projectDir, {
1123
+ bindingSourceEntries: [buildBindingSourceConfigEntry(bindingSourceSlug)],
1124
+ });
1125
+ return {
1126
+ bindingSourceSlug,
1127
+ projectDir: workspace.projectDir,
1128
+ };
1129
+ }
1130
+ catch (error) {
1131
+ await rollbackWorkspaceMutation(mutationSnapshot);
1132
+ throw error;
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Add one `blockHooks` entry to an existing official workspace block.
1137
+ *
1138
+ * @param options Command options for the hooked-block workflow.
1139
+ * @param options.anchorBlockName Full block name that will anchor the insertion.
1140
+ * @param options.blockName Existing workspace block slug to patch.
1141
+ * @param options.cwd Working directory used to resolve the nearest official workspace.
1142
+ * Defaults to `process.cwd()`.
1143
+ * @param options.position Hook position to store in `block.json`.
1144
+ * @returns A promise that resolves with the normalized target block slug, anchor
1145
+ * block name, position, and owning project directory after `block.json` is written.
1146
+ * @throws {Error} When the command is run outside an official workspace, when
1147
+ * the target block is unknown, when required flags are missing, or when the
1148
+ * block already defines a hook for the requested anchor.
1149
+ */
1150
+ export async function runAddHookedBlockCommand({ anchorBlockName, blockName, cwd = process.cwd(), position, }) {
1151
+ const workspace = resolveWorkspaceProject(cwd);
1152
+ const blockSlug = normalizeBlockSlug(blockName);
1153
+ const inventory = readWorkspaceInventory(workspace.projectDir);
1154
+ resolveWorkspaceBlock(inventory, blockSlug);
1155
+ const resolvedAnchorBlockName = assertValidHookAnchor(anchorBlockName);
1156
+ const resolvedPosition = assertValidHookedBlockPosition(position);
1157
+ const selfHookAnchor = `${workspace.workspace.namespace}/${blockSlug}`;
1158
+ if (resolvedAnchorBlockName === selfHookAnchor) {
1159
+ throw new Error("`wp-typia add hooked-block` cannot hook a block relative to its own block name.");
1160
+ }
1161
+ const { blockJson, blockJsonPath } = readWorkspaceBlockJson(workspace.projectDir, blockSlug);
1162
+ const blockJsonRelativePath = path.relative(workspace.projectDir, blockJsonPath);
1163
+ const blockHooks = getMutableBlockHooks(blockJson, blockJsonRelativePath);
1164
+ if (Object.prototype.hasOwnProperty.call(blockHooks, resolvedAnchorBlockName)) {
1165
+ throw new Error(`${blockJsonRelativePath} already defines a blockHooks entry for "${resolvedAnchorBlockName}".`);
1166
+ }
1167
+ const mutationSnapshot = {
1168
+ fileSources: await snapshotWorkspaceFiles([blockJsonPath]),
1169
+ snapshotDirs: [],
1170
+ targetPaths: [],
1171
+ };
1172
+ try {
1173
+ blockHooks[resolvedAnchorBlockName] = resolvedPosition;
1174
+ await fsp.writeFile(blockJsonPath, JSON.stringify(blockJson, null, "\t"), "utf8");
1175
+ return {
1176
+ anchorBlockName: resolvedAnchorBlockName,
1177
+ blockSlug,
1178
+ position: resolvedPosition,
1179
+ projectDir: workspace.projectDir,
1180
+ };
1181
+ }
1182
+ catch (error) {
1183
+ await rollbackWorkspaceMutation(mutationSnapshot);
1184
+ throw error;
1185
+ }
561
1186
  }
1187
+ export { getWorkspaceBlockSelectOptions };