soinproduction-gutenberg 0.1.2 → 0.1.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.
- package/README.md +12 -0
- package/adapters/next/runtime.php +25 -0
- package/bootstrap.php +1 -0
- package/dist/adapters/next/runtime.php +25 -0
- package/dist/bootstrap.php +1 -0
- package/dist/tooling/cli.mjs +36 -22
- package/dist/tooling/create-module.mjs +3 -3
- package/dist/tooling/create-section.mjs +16 -23
- package/dist/tooling/dev.mjs +59 -0
- package/dist/tooling/materialize-source.mjs +25 -0
- package/dist/tooling/next-runtime.mjs +61 -0
- package/dist/tooling/prepare-project.mjs +28 -0
- package/dist/tooling/render-module.mjs +7 -7
- package/dist/tooling/sync-blocks.mjs +6 -2
- package/dist/tooling/watch-editor.mjs +122 -0
- package/package.json +1 -1
- package/tooling/cli.mjs +36 -22
- package/tooling/create-module.mjs +3 -3
- package/tooling/create-section.mjs +16 -23
- package/tooling/dev.mjs +59 -0
- package/tooling/materialize-source.mjs +25 -0
- package/tooling/next-runtime.mjs +61 -0
- package/tooling/prepare-project.mjs +28 -0
- package/tooling/render-module.mjs +7 -7
- package/tooling/sync-blocks.mjs +6 -2
- package/tooling/watch-editor.mjs +122 -0
package/README.md
CHANGED
|
@@ -74,3 +74,15 @@ npm pack --dry-run
|
|
|
74
74
|
CI checks types, isolated component-connection tests, package exports, PHP syntax and packaging. Push a matching `vX.Y.Z` tag to publish version `X.Y.Z` automatically. See [RELEASING.md](RELEASING.md) for one-time npm trusted-publisher setup.
|
|
75
75
|
|
|
76
76
|
Source is published without an open-source license grant (`UNLICENSED`).
|
|
77
|
+
|
|
78
|
+
## Project commands
|
|
79
|
+
|
|
80
|
+
Use the installed `soinproduction-kit` binary in npm scripts:
|
|
81
|
+
|
|
82
|
+
```json
|
|
83
|
+
{"scripts":{"dev":"soinproduction-kit dev","start":"soinproduction-kit start","create:component":"soinproduction-kit create component","create:section":"soinproduction-kit create section","create:layout":"soinproduction-kit create layout","new:section":"soinproduction-kit new section","render:module":"soinproduction-kit render"}}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`dev` and `start` select a free port automatically. Explicit `--port`/`-p` or `PORT` take precedence. Development propagates the actual origin to site/forms configuration and writes `build/next-server.json`; the Next PHP adapter loaded by `bootstrap.php` reads it for local frontend URLs. Public deployment URLs stay configured. Override the project-relative runtime path with `runtime.file` in `kit.config.json`.
|
|
87
|
+
|
|
88
|
+
Generators prepare the installed kit automatically, then create the component schema, renderer, editor, PHP registration, styles and preview in the project. `new section` creates a declarative section. Use `--no-build` to generate without an editor build. `render` regenerates module markup from its schema. All commands accept `--project PATH`. The project owns component/section selection and optional `adapters.contentRenderer` / `adapters.editorAdapter` objects (`from`, `export`); portable defaults are provided. Preparation reuses unchanged package sources and refreshes generated connections without disturbing a running Next watcher.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
namespace SiteTheme\Kit;
|
|
3
|
+
defined('ABSPATH') || exit;
|
|
4
|
+
|
|
5
|
+
/** A local Next process advertises its actual port; public deployments use the configured URL. */
|
|
6
|
+
function frontend_origin(?string $configured = null, ?string $runtime_file = null): string {
|
|
7
|
+
$configured = rtrim($configured ?? (defined('SITE_FRONTEND_URL') ? SITE_FRONTEND_URL : ''), '/');
|
|
8
|
+
$local = ['127.0.0.1', 'localhost', '[::1]', '::1'];
|
|
9
|
+
if (!in_array(parse_url($configured, PHP_URL_HOST), $local, true)) return $configured;
|
|
10
|
+
$root = dirname(__DIR__, 3);
|
|
11
|
+
$config_file = $root . '/kit.config.json';
|
|
12
|
+
$config = is_readable($config_file) ? json_decode((string)file_get_contents($config_file), true) : [];
|
|
13
|
+
$relative = $config['runtime']['file'] ?? 'build/next-server.json';
|
|
14
|
+
if ($runtime_file === null && (!is_string($relative) || str_starts_with($relative, '/') || in_array('..', explode('/', str_replace('\\', '/', $relative)), true))) return $configured;
|
|
15
|
+
$file = $runtime_file ?? $root . '/' . $relative;
|
|
16
|
+
$runtime = is_readable($file) ? json_decode((string)file_get_contents($file), true) : null;
|
|
17
|
+
if (!is_array($runtime) || !is_string($runtime['origin'] ?? null) || !is_int($runtime['pid'] ?? null) || $runtime['pid'] < 1) return $configured;
|
|
18
|
+
$url = parse_url($runtime['origin']);
|
|
19
|
+
if (!is_array($url) || !in_array($url['scheme'] ?? '', ['http', 'https'], true)
|
|
20
|
+
|| !in_array($url['host'] ?? '', $local, true) || empty($url['port'])
|
|
21
|
+
|| $url['port'] < 1 || $url['port'] > 65535 || isset($url['user']) || isset($url['pass'])
|
|
22
|
+
|| isset($url['query']) || isset($url['fragment']) || !empty($url['path'])) return $configured;
|
|
23
|
+
if (function_exists('posix_kill') && !@posix_kill((int)$runtime['pid'], 0) && posix_get_last_error() === 3) return $configured;
|
|
24
|
+
return rtrim($runtime['origin'], '/');
|
|
25
|
+
}
|
package/bootstrap.php
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
namespace SiteTheme\Kit;
|
|
3
3
|
defined('ABSPATH') || exit;
|
|
4
4
|
/** One host connection; generated entries belong to components and modules. */
|
|
5
|
+
require_once __DIR__.'/adapters/next/runtime.php';
|
|
5
6
|
require_once __DIR__.'/admin-ui/bootstrap.php';
|
|
6
7
|
foreach (require __DIR__.'/generated/modules.php' as $entry) {
|
|
7
8
|
require_once __DIR__.'/'.$entry;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
namespace SiteTheme\Kit;
|
|
3
|
+
defined('ABSPATH') || exit;
|
|
4
|
+
|
|
5
|
+
/** A local Next process advertises its actual port; public deployments use the configured URL. */
|
|
6
|
+
function frontend_origin(?string $configured = null, ?string $runtime_file = null): string {
|
|
7
|
+
$configured = rtrim($configured ?? (defined('SITE_FRONTEND_URL') ? SITE_FRONTEND_URL : ''), '/');
|
|
8
|
+
$local = ['127.0.0.1', 'localhost', '[::1]', '::1'];
|
|
9
|
+
if (!in_array(parse_url($configured, PHP_URL_HOST), $local, true)) return $configured;
|
|
10
|
+
$root = dirname(__DIR__, 3);
|
|
11
|
+
$config_file = $root . '/kit.config.json';
|
|
12
|
+
$config = is_readable($config_file) ? json_decode((string)file_get_contents($config_file), true) : [];
|
|
13
|
+
$relative = $config['runtime']['file'] ?? 'build/next-server.json';
|
|
14
|
+
if ($runtime_file === null && (!is_string($relative) || str_starts_with($relative, '/') || in_array('..', explode('/', str_replace('\\', '/', $relative)), true))) return $configured;
|
|
15
|
+
$file = $runtime_file ?? $root . '/' . $relative;
|
|
16
|
+
$runtime = is_readable($file) ? json_decode((string)file_get_contents($file), true) : null;
|
|
17
|
+
if (!is_array($runtime) || !is_string($runtime['origin'] ?? null) || !is_int($runtime['pid'] ?? null) || $runtime['pid'] < 1) return $configured;
|
|
18
|
+
$url = parse_url($runtime['origin']);
|
|
19
|
+
if (!is_array($url) || !in_array($url['scheme'] ?? '', ['http', 'https'], true)
|
|
20
|
+
|| !in_array($url['host'] ?? '', $local, true) || empty($url['port'])
|
|
21
|
+
|| $url['port'] < 1 || $url['port'] > 65535 || isset($url['user']) || isset($url['pass'])
|
|
22
|
+
|| isset($url['query']) || isset($url['fragment']) || !empty($url['path'])) return $configured;
|
|
23
|
+
if (function_exists('posix_kill') && !@posix_kill((int)$runtime['pid'], 0) && posix_get_last_error() === 3) return $configured;
|
|
24
|
+
return rtrim($runtime['origin'], '/');
|
|
25
|
+
}
|
package/dist/bootstrap.php
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
namespace SiteTheme\Kit;
|
|
3
3
|
defined('ABSPATH') || exit;
|
|
4
4
|
/** One host connection; generated entries belong to components and modules. */
|
|
5
|
+
require_once __DIR__.'/adapters/next/runtime.php';
|
|
5
6
|
require_once __DIR__.'/admin-ui/bootstrap.php';
|
|
6
7
|
foreach (require __DIR__.'/generated/modules.php' as $entry) {
|
|
7
8
|
require_once __DIR__.'/'.$entry;
|
package/dist/tooling/cli.mjs
CHANGED
|
@@ -1,29 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import fs from 'node:fs';
|
|
3
2
|
import path from 'node:path';
|
|
4
|
-
import {fileURLToPath} from 'node:url';
|
|
5
|
-
import {
|
|
6
|
-
import {syncKit} from './sync-kit.mjs';
|
|
7
|
-
const source=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
|
|
3
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
4
|
+
import {prepareProject} from './prepare-project.mjs';
|
|
8
5
|
const command=process.argv[2]??'help';
|
|
9
|
-
const
|
|
10
|
-
|
|
6
|
+
const input=process.argv.slice(3),args=[];
|
|
7
|
+
let root=process.cwd();
|
|
8
|
+
for(let i=0;i<input.length;i++){
|
|
9
|
+
if(input[i]==='--project'){if(!input[i+1])throw new Error('--project needs a path');root=input[++i];}
|
|
10
|
+
else if(input[i].startsWith('--project='))root=input[i].slice(10);
|
|
11
|
+
else args.push(input[i]);
|
|
12
|
+
}
|
|
13
|
+
root=path.resolve(root);
|
|
14
|
+
const noBuild=args.includes('--no-build');
|
|
15
|
+
const positional=args.filter(value=>!value.startsWith('--'));
|
|
11
16
|
if(command==='prepare'){
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
if(
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
console.log(
|
|
17
|
+
const result=prepareProject(root,{force:args.includes('--force')});
|
|
18
|
+
console.log(`Prepared kit ${result.version} in ${result.directory}`);
|
|
19
|
+
}else if(command==='dev'||command==='start'){
|
|
20
|
+
const {runDev,runStart}=await import('./dev.mjs');
|
|
21
|
+
await (command==='dev'?runDev:runStart)({root,args});
|
|
22
|
+
}else if(['build:editor','build:wordpress','build:booking'].includes(command)){
|
|
23
|
+
prepareProject(root);process.chdir(root);
|
|
24
|
+
await import(pathToFileURL(path.join(root,'kit/tooling/'+command.replace(':','-')+'.mjs')).href);
|
|
25
|
+
}else if(command==='create'||['create:component','create:section','create:layout'].includes(command)){
|
|
26
|
+
prepareProject(root);
|
|
27
|
+
const kind=command==='create'?positional[0]:command.split(':')[1];
|
|
28
|
+
const slug=command==='create'?positional[1]:positional[0];
|
|
29
|
+
const {createModule}=await import('./create-module.mjs');
|
|
30
|
+
const result=createModule(root,kind,slug,{build:!noBuild});console.log(`Created ${result.name}\n${result.directory}`);
|
|
31
|
+
}else if(command==='new:section'||(command==='new'&&positional[0]==='section')){
|
|
32
|
+
prepareProject(root);
|
|
33
|
+
const {createSection}=await import('./create-section.mjs');
|
|
34
|
+
const result=createSection(root,command==='new'?positional[1]:positional[0]);console.log(`Created ${result.name}\n${result.directory}`);
|
|
35
|
+
}else if(command==='render'||command==='render:module'){
|
|
36
|
+
prepareProject(root);
|
|
37
|
+
const {renderModule}=await import('./render-module.mjs');
|
|
38
|
+
const output=renderModule(root,positional[0],{build:!noBuild,force:args.includes('--force'),stdout:args.includes('--stdout')});
|
|
39
|
+
console.log(output);
|
|
26
40
|
}else{
|
|
27
|
-
console.log(
|
|
41
|
+
console.log(`Usage: soinproduction-kit COMMAND [--project PATH]\n\n prepare [--force]\n dev [Next options] Dynamic port and optional editor watcher\n start [Next options] Dynamic production port\n create component NAME [--no-build]\n create section NAME [--no-build] Schema-based block\n create layout NAME [--no-build]\n new section NAME Declarative kit section\n render NAME [--stdout|--force] [--no-build]\n build:editor | build:wordpress | build:booking`);
|
|
28
42
|
if(command!=='help')process.exitCode=1;
|
|
29
43
|
}
|
|
@@ -64,7 +64,7 @@ return ['id'=>'${slug}','group'=>'custom','name'=>'${name}','title'=>'${title}',
|
|
|
64
64
|
php = path.resolve(root, '../inc/blocks/registry.php'),
|
|
65
65
|
css = path.join(root, 'app/globals.css');
|
|
66
66
|
const original = new Map(
|
|
67
|
-
[registry, editor, php, css].map((f) => [f, fs.readFileSync(f, 'utf8')])
|
|
67
|
+
[registry, editor, php, css].map((f) => [f, fs.existsSync(f)?fs.readFileSync(f, 'utf8'):null])
|
|
68
68
|
);
|
|
69
69
|
try {
|
|
70
70
|
fs.mkdirSync(directory, { recursive: true });
|
|
@@ -72,9 +72,9 @@ return ['id'=>'${slug}','group'=>'custom','name'=>'${name}','title'=>'${title}',
|
|
|
72
72
|
fs.writeFileSync(path.join(directory, file), text);
|
|
73
73
|
renderModule(root, slug, { build: false });
|
|
74
74
|
syncSections(root);
|
|
75
|
-
if (build) execFileSync(
|
|
75
|
+
if (build) execFileSync(process.execPath, [path.join(root,'kit/tooling/build-editor.mjs')], { cwd: root, stdio: 'inherit' });
|
|
76
76
|
} catch (error) {
|
|
77
|
-
for (const [file, text] of original) fs.writeFileSync(file,
|
|
77
|
+
for (const [file, text] of original) {if(text===null)fs.rmSync(file,{force:true});else fs.writeFileSync(file,text);}
|
|
78
78
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
79
79
|
throw error;
|
|
80
80
|
}
|
|
@@ -1,25 +1,18 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const directory
|
|
8
|
-
if
|
|
9
|
-
const title
|
|
10
|
-
fs.mkdirSync(directory,
|
|
11
|
-
|
|
12
|
-
fs.writeFileSync(path.join(directory,
|
|
13
|
-
import meta from './section.json';
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
<Text name="text" className="mt-4" />
|
|
20
|
-
</div>
|
|
21
|
-
</Section>
|
|
22
|
-
));
|
|
23
|
-
`);
|
|
24
|
-
syncSections();
|
|
25
|
-
console.log(`Created ${directory}. Run npm run build:editor and refresh Gutenberg.`);
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {syncSections} from './sync-sections.mjs';
|
|
5
|
+
export function createSection(root,slug){
|
|
6
|
+
if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(slug??''))throw new Error('Use a lowercase name, for example consultation.');
|
|
7
|
+
const folder='section-'+slug.replace(/^section-/,''),directory=path.join(root,'src/sections',folder);
|
|
8
|
+
if(fs.existsSync(directory))throw new Error(`${folder} already exists; nothing was overwritten.`);
|
|
9
|
+
const title=slug.replace(/^section-/,'').replace(/-/g,' ').replace(/^./,c=>c.toUpperCase());
|
|
10
|
+
fs.mkdirSync(directory,{recursive:true});
|
|
11
|
+
try{
|
|
12
|
+
fs.writeFileSync(path.join(directory,'section.json'),JSON.stringify({slug:folder,title},null,2)+'\n');
|
|
13
|
+
fs.writeFileSync(path.join(directory,'section.tsx'),`import {Heading,Section,Text,section} from '@kit';\nimport meta from './section.json';\nexport default section(meta,()=> (\n <Section className="py-20">\n <div className="mx-auto max-w-7xl px-6">\n <Heading name="title" className="text-4xl"/>\n <Text name="text" className="mt-4"/>\n </div>\n </Section>\n));\n`);
|
|
14
|
+
syncSections(root);
|
|
15
|
+
}catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
16
|
+
return {directory,name:'site/'+folder};
|
|
17
|
+
}
|
|
18
|
+
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))console.log(createSection(process.cwd(),process.argv[2]).directory);
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {spawn} from 'node:child_process';
|
|
4
|
+
import {createRequire} from 'node:module';
|
|
5
|
+
import {prepareProject} from './prepare-project.mjs';
|
|
6
|
+
import {buildEditor,watchEditor} from './watch-editor.mjs';
|
|
7
|
+
import {nextRuntime,writeRuntime,clearRuntime} from './next-runtime.mjs';
|
|
8
|
+
|
|
9
|
+
export function renderMode(root){
|
|
10
|
+
const file=path.resolve(root,'../render.config.json');
|
|
11
|
+
const config=fs.existsSync(file)?JSON.parse(fs.readFileSync(file,'utf8')):{};
|
|
12
|
+
const mode=config.mode??'next';
|
|
13
|
+
if(!['next','wordpress'].includes(mode))throw new Error('render.config.json: mode must be next or wordpress');
|
|
14
|
+
return mode;
|
|
15
|
+
}
|
|
16
|
+
export async function runDev({root=process.cwd(),args=process.argv.slice(2),env=process.env}={}){
|
|
17
|
+
root=path.resolve(root);
|
|
18
|
+
const configFile=path.join(root,'kit.config.json');
|
|
19
|
+
const config=fs.existsSync(configFile)?JSON.parse(fs.readFileSync(configFile,'utf8')):{};
|
|
20
|
+
if(fs.existsSync(configFile))prepareProject(root);
|
|
21
|
+
const mode=renderMode(root);console.log(`[dev] Renderer: ${mode}`);
|
|
22
|
+
const editor=(config.editor?.entry||mode==='wordpress')?watchEditor({root,build:async({signal})=>{
|
|
23
|
+
await buildEditor(root,{signal});
|
|
24
|
+
if(mode==='wordpress')await new Promise((resolve,reject)=>{
|
|
25
|
+
const child=spawn(process.execPath,[path.join(root,'kit/tooling/build-wordpress.mjs')],{cwd:root,stdio:'inherit',signal});
|
|
26
|
+
child.once('error',reject);child.once('close',code=>code===0?resolve():reject(new Error('WordPress build failed')));
|
|
27
|
+
});
|
|
28
|
+
}}):{ready:Promise.resolve(),close:async()=>{}};
|
|
29
|
+
let next=null,stopping=false;
|
|
30
|
+
const stop=async(code,signal='SIGTERM')=>{
|
|
31
|
+
if(stopping)return;stopping=true;process.exitCode=code;clearRuntime(root);
|
|
32
|
+
if(next&&next.exitCode===null&&next.signalCode===null)next.kill(signal);
|
|
33
|
+
await editor.close();
|
|
34
|
+
};
|
|
35
|
+
process.once('SIGINT',()=>void stop(130,'SIGINT'));
|
|
36
|
+
process.once('SIGTERM',()=>void stop(143));
|
|
37
|
+
await editor.ready;
|
|
38
|
+
if(!stopping&&mode==='next'){
|
|
39
|
+
const runtime=await nextRuntime({args,env});
|
|
40
|
+
if(stopping)return {stop};
|
|
41
|
+
writeRuntime(root,runtime);console.log(`[dev] Frontend: ${runtime.origin}`);
|
|
42
|
+
const require=createRequire(path.join(root,'package.json'));
|
|
43
|
+
next=spawn(process.execPath,[require.resolve('next/dist/bin/next'),'dev',...runtime.args],{cwd:root,stdio:'inherit',env:runtime.env});
|
|
44
|
+
next.once('error',error=>{console.error('[dev] Could not start Next.js:',error.message);void stop(1);});
|
|
45
|
+
next.once('close',(code,signal)=>void stop(code??(signal?1:0)));
|
|
46
|
+
}
|
|
47
|
+
return {next,editor,stop};
|
|
48
|
+
}
|
|
49
|
+
export async function runStart({root=process.cwd(),args=process.argv.slice(2),env=process.env}={}){
|
|
50
|
+
root=path.resolve(root);const runtime=await nextRuntime({args,env,mode:'start'});
|
|
51
|
+
console.log(`[start] Frontend: ${runtime.origin}`);writeRuntime(root,runtime);
|
|
52
|
+
const require=createRequire(path.join(root,'package.json'));
|
|
53
|
+
const next=spawn(process.execPath,[require.resolve('next/dist/bin/next'),'start',...runtime.args],{cwd:root,stdio:'inherit',env:runtime.env});
|
|
54
|
+
const stop=signal=>{clearRuntime(root);next.kill(signal);};
|
|
55
|
+
process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
|
|
56
|
+
next.once('error',error=>{clearRuntime(root);console.error(error);process.exitCode=1;});
|
|
57
|
+
next.once('close',code=>{clearRuntime(root);process.exitCode=code??1;});
|
|
58
|
+
return {next,runtime,stop};
|
|
59
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
/** The distributed ESM uses .js paths; a host TS source copy must resolve TS files. */
|
|
5
|
+
export function normalizeSourceImports(directory){
|
|
6
|
+
const walk=folder=>fs.readdirSync(folder,{withFileTypes:true}).flatMap(entry=>entry.isDirectory()?walk(path.join(folder,entry.name)):[path.join(folder,entry.name)]);
|
|
7
|
+
for(const file of walk(directory).filter(file=>/\.tsx?$/.test(file))){
|
|
8
|
+
let text=fs.readFileSync(file,'utf8');
|
|
9
|
+
const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true),edits=[];
|
|
10
|
+
const visit=node=>{
|
|
11
|
+
let specifier;
|
|
12
|
+
if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier))specifier=node.moduleSpecifier;
|
|
13
|
+
if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword&&ts.isStringLiteral(node.arguments[0]))specifier=node.arguments[0];
|
|
14
|
+
if(ts.isImportTypeNode(node)&&ts.isLiteralTypeNode(node.argument)&&ts.isStringLiteral(node.argument.literal))specifier=node.argument.literal;
|
|
15
|
+
if(specifier&&specifier.text.startsWith('.')&&specifier.text.endsWith('.js')){
|
|
16
|
+
const base=path.resolve(path.dirname(file),specifier.text.slice(0,-3));
|
|
17
|
+
if(['.ts','.tsx'].some(extension=>fs.existsSync(base+extension)))edits.push({start:specifier.getStart(source)+1,end:specifier.getEnd()-1,value:specifier.text.slice(0,-3)});
|
|
18
|
+
}
|
|
19
|
+
ts.forEachChild(node,visit);
|
|
20
|
+
};
|
|
21
|
+
visit(source);
|
|
22
|
+
for(const edit of edits.sort((a,b)=>b.start-a.start))text=text.slice(0,edit.start)+edit.value+text.slice(edit.end);
|
|
23
|
+
if(edits.length)fs.writeFileSync(file,text);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import net from 'node:net';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
function option(args,names){
|
|
6
|
+
for(let index=0;index<args.length;index++){
|
|
7
|
+
const value=args[index];
|
|
8
|
+
if(names.includes(value)){if(args[index+1]===undefined)throw new Error('Missing value for '+value);return args[index+1];}
|
|
9
|
+
for(const name of names)if(value.startsWith(name+'='))return value.slice(name.length+1);
|
|
10
|
+
if(names.includes('-p')&&/^-p\d+$/.test(value))return value.slice(2);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function withoutPort(args){
|
|
14
|
+
return args.filter((value,index)=>!['--port','-p'].includes(value)&&!['--port','-p'].includes(args[index-1])&&!/^--port=|^-p=|^-p\d+$/.test(value));
|
|
15
|
+
}
|
|
16
|
+
export function availablePort(host='0.0.0.0'){
|
|
17
|
+
return new Promise((resolve,reject)=>{
|
|
18
|
+
const server=net.createServer();server.once('error',reject);
|
|
19
|
+
server.listen({host,port:0,exclusive:true},()=>{
|
|
20
|
+
const port=server.address().port;
|
|
21
|
+
server.close(error=>error?reject(error):resolve(port));
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export async function nextRuntime({args=[],env=process.env,mode='dev',findPort=availablePort}={}){
|
|
26
|
+
const host=option(args,['--hostname','-H'])??'0.0.0.0';
|
|
27
|
+
const requested=option(args,['--port','-p'])??env.PORT;
|
|
28
|
+
if(requested!==undefined&&!/^\d+$/.test(String(requested)))throw new Error('Next port must be an integer from 0 to 65535');
|
|
29
|
+
let port=requested===undefined?0:Number(requested);
|
|
30
|
+
if(port>65535)throw new Error('Next port must be an integer from 0 to 65535');
|
|
31
|
+
if(port===0)port=await findPort(host);
|
|
32
|
+
const hostname=['0.0.0.0','::'].includes(host)?'127.0.0.1':host;
|
|
33
|
+
const protocol=args.includes('--experimental-https')?'https':'http';
|
|
34
|
+
const origin=`${protocol}://${hostname.includes(':')?'['+hostname+']':hostname}:${port}`;
|
|
35
|
+
const childEnv={...env,PORT:String(port)};
|
|
36
|
+
if(mode==='dev'){
|
|
37
|
+
childEnv.NEXT_PUBLIC_SITE_URL=origin;
|
|
38
|
+
childEnv.FORM_ENGINE_ORIGIN=origin;
|
|
39
|
+
}
|
|
40
|
+
return {args:[...withoutPort(args),'--port',String(port)],env:childEnv,port,origin};
|
|
41
|
+
}
|
|
42
|
+
export function runtimeFile(root){
|
|
43
|
+
const configFile=path.join(root,'kit.config.json');
|
|
44
|
+
const config=fs.existsSync(configFile)?JSON.parse(fs.readFileSync(configFile,'utf8')):{};
|
|
45
|
+
const value=config.runtime?.file??'build/next-server.json';
|
|
46
|
+
if(typeof value!=='string')throw new Error('runtime.file must be a project-relative path');
|
|
47
|
+
const file=path.resolve(root,value);
|
|
48
|
+
if(!file.startsWith(path.resolve(root)+path.sep))throw new Error('runtime.file must stay inside the project');
|
|
49
|
+
return file;
|
|
50
|
+
}
|
|
51
|
+
export function writeRuntime(root,runtime,pid=process.pid){
|
|
52
|
+
const file=runtimeFile(root);
|
|
53
|
+
fs.mkdirSync(path.dirname(file),{recursive:true});
|
|
54
|
+
const temporary=file+'.'+pid+'.tmp';
|
|
55
|
+
fs.writeFileSync(temporary,JSON.stringify({origin:runtime.origin,port:runtime.port,pid})+'\n');
|
|
56
|
+
fs.renameSync(temporary,file);
|
|
57
|
+
}
|
|
58
|
+
export function clearRuntime(root,pid=process.pid){
|
|
59
|
+
const file=runtimeFile(root);
|
|
60
|
+
try{if(JSON.parse(fs.readFileSync(file,'utf8')).pid===pid)fs.unlinkSync(file);}catch(error){if(error.code!=='ENOENT'&&!(error instanceof SyntaxError))console.error('[next] Could not clear runtime address:',error.message);}
|
|
61
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {syncSections} from './sync-sections.mjs';
|
|
5
|
+
import {syncKit} from './sync-kit.mjs';
|
|
6
|
+
import {normalizeSourceImports} from './materialize-source.mjs';
|
|
7
|
+
export const packageRoot=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
|
|
8
|
+
const hasFiles=folder=>fs.readdirSync(folder,{withFileTypes:true}).some(entry=>entry.isDirectory()?hasFiles(path.join(folder,entry.name)):true);
|
|
9
|
+
|
|
10
|
+
/** Keep watched source files stable; only refresh the source copy when the installed version changes. */
|
|
11
|
+
export function prepareProject(project=process.cwd(),{force=false}={}){
|
|
12
|
+
const root=path.resolve(project),destination=path.join(root,'kit'),markerFile=path.join(destination,'.kit-package.json');
|
|
13
|
+
const metadata=JSON.parse(fs.readFileSync(path.join(packageRoot,'package.json'),'utf8'));
|
|
14
|
+
let marker;try{marker=JSON.parse(fs.readFileSync(markerFile,'utf8'));}catch{}
|
|
15
|
+
const required=['index.tsx','core/fields/render.tsx','editor/seo.ts','tooling/sync-sections.mjs','tooling/sync-kit.mjs'];
|
|
16
|
+
const reusable=!force&&marker?.name===metadata.name&&marker?.version===metadata.version&&required.every(file=>fs.existsSync(path.join(destination,file)));
|
|
17
|
+
if(!reusable&&destination!==packageRoot){
|
|
18
|
+
if(fs.existsSync(destination)&&!marker&&hasFiles(destination))throw new Error('kit/ is authored source. Move it aside before preparing the npm-managed kit copy.');
|
|
19
|
+
fs.mkdirSync(destination,{recursive:true});
|
|
20
|
+
const folders=['components','editor','core','ui','admin-ui','modules','adapters','hooks','styles','schema','shared','tooling'];
|
|
21
|
+
for(const folder of folders){fs.rmSync(path.join(destination,folder),{recursive:true,force:true});fs.cpSync(path.join(packageRoot,folder),path.join(destination,folder),{recursive:true});}
|
|
22
|
+
for(const file of ['index.tsx','bootstrap.php'])fs.copyFileSync(path.join(packageRoot,file),path.join(destination,file));
|
|
23
|
+
normalizeSourceImports(destination);
|
|
24
|
+
fs.writeFileSync(markerFile,JSON.stringify({name:metadata.name,version:metadata.version},null,2)+'\n');
|
|
25
|
+
}
|
|
26
|
+
syncSections(root);syncKit(root,{directory:destination});
|
|
27
|
+
return {root,directory:destination,version:metadata.version,refreshed:!reusable};
|
|
28
|
+
}
|
|
@@ -10,19 +10,19 @@ import {buildSync} from 'esbuild';
|
|
|
10
10
|
const project = process.cwd();
|
|
11
11
|
const quote = JSON.stringify;
|
|
12
12
|
|
|
13
|
-
export function loadSchema(file) {
|
|
13
|
+
export function loadSchema(file, root = process.cwd()) {
|
|
14
14
|
const source = `import {schema} from ${quote(file)};import {validateFields} from ${quote(
|
|
15
|
-
path.join(
|
|
15
|
+
path.join(root, 'kit/core/fields/schema.ts')
|
|
16
16
|
)};export default validateFields(schema);`;
|
|
17
17
|
const result = buildSync({
|
|
18
|
-
stdin: {contents: source, resolveDir:
|
|
18
|
+
stdin: {contents: source, resolveDir: root, loader: 'ts'},
|
|
19
19
|
bundle: true,
|
|
20
20
|
write: false,
|
|
21
21
|
platform: 'node',
|
|
22
22
|
format: 'cjs',
|
|
23
23
|
packages: 'external',
|
|
24
|
-
tsconfig: path.join(
|
|
25
|
-
alias: {'@': path.join(
|
|
24
|
+
tsconfig: path.join(root, 'tsconfig.json'),
|
|
25
|
+
alias: {'@': path.join(root, 'src')},
|
|
26
26
|
});
|
|
27
27
|
const module = {exports: {}};
|
|
28
28
|
new Function('module', 'exports', 'require', result.outputFiles[0].text)(
|
|
@@ -110,7 +110,7 @@ export function renderModule(root, slug, {build = true, force = false, stdout =
|
|
|
110
110
|
throw new Error(`No schema.ts in ${slug}. Only schema-based modules support this command.`);
|
|
111
111
|
const registration = fs.readFileSync(path.join(directory, 'register.php'), 'utf8');
|
|
112
112
|
const kind = /'kind'\s*=>\s*'(component|layout)'/.exec(registration)?.[1] ?? 'section';
|
|
113
|
-
const markup = generateMarkup(loadSchema(file), slug, kind);
|
|
113
|
+
const markup = generateMarkup(loadSchema(file, root), slug, kind);
|
|
114
114
|
if (stdout) return markup;
|
|
115
115
|
const output = path.join(directory, 'component.tsx'),
|
|
116
116
|
previous = fs.existsSync(output) ? fs.readFileSync(output, 'utf8') : null;
|
|
@@ -122,7 +122,7 @@ export function renderModule(root, slug, {build = true, force = false, stdout =
|
|
|
122
122
|
);
|
|
123
123
|
try {
|
|
124
124
|
fs.writeFileSync(output, '// Generated layout sha256:' + hash(markup) + '\n' + markup);
|
|
125
|
-
if (build) execFileSync(
|
|
125
|
+
if (build) execFileSync(process.execPath, [path.join(root,'kit/tooling/build-editor.mjs')], {cwd: root, stdio: 'inherit'});
|
|
126
126
|
} catch (error) {
|
|
127
127
|
if (previous === null) fs.rmSync(output, {force: true});
|
|
128
128
|
else fs.writeFileSync(output, previous);
|
|
@@ -21,9 +21,13 @@ export function syncBlocks(root=process.cwd()) {
|
|
|
21
21
|
entries.push(`defineModule({...${symbol}Info,schema:${symbol}Schema,Component:${symbol}Component})`);
|
|
22
22
|
editEntries.push(`{definition:definitions.get(${symbol}Info.name)!,Edit:${symbol}Edit}`);
|
|
23
23
|
});
|
|
24
|
+
const configFile=path.join(root,'kit.config.json');
|
|
25
|
+
const config=fs.existsSync(configFile)?JSON.parse(fs.readFileSync(configFile,'utf8')):{};
|
|
26
|
+
const content=config.adapters?.contentRenderer??(fs.existsSync(path.join(root,'src/site/rendering/native-content.tsx'))?{from:'@/site/rendering/native-content',export:'NativeContent'}:{from:'@kit/core/content/areas/render',export:'NativeAreaContent'});
|
|
27
|
+
const editor=config.adapters?.editorAdapter??(fs.existsSync(path.join(root,'src/site/editor/module-editor.tsx'))?{from:'@/site/editor/module-editor',export:'SchemaEditor'}:{from:'@kit/core/fields/editor',export:'SchemaEditor'});
|
|
24
28
|
const warning='// Generated by kit/tooling/sync-blocks.mjs. Do not edit.\n';
|
|
25
|
-
write(path.join(root,'src/blocks/registry.ts'),warning+`import {sections} from '@/sections/index.generated';\nimport {defineModule as defineCoreModule} from '@kit/core/modules/define-module';\nimport {NativeContent} from '
|
|
26
|
-
write(path.join(root,'src/blocks/editor-registry.ts'),warning+`import {createElement} from 'react';\nimport {sections} from '@/sections/index.generated';\nimport {SchemaEditor} from '
|
|
29
|
+
write(path.join(root,'src/blocks/registry.ts'),warning+`import {sections} from '@/sections/index.generated';\nimport {defineModule as defineCoreModule} from '@kit/core/modules/define-module';\nimport {${content.export} as NativeContent} from '${content.from}';\nimport type {ModuleDefinition} from '@kit/core/modules/types';\nconst defineModule=(config:Parameters<typeof defineCoreModule>[0])=>defineCoreModule({...config,Content:NativeContent});\n${imports.join('\n')}\nlet modules: ModuleDefinition[];\nexport function getModules(){return modules??=( [${entries.join(',\n')},...sections.map(module=>defineModule(module))]);}\n`);
|
|
30
|
+
write(path.join(root,'src/blocks/editor-registry.ts'),warning+`import {createElement} from 'react';\nimport {sections} from '@/sections/index.generated';\nimport {${editor.export} as SchemaEditor} from '${editor.from}';\nimport {getModules} from './registry';\n${editors.join('\n')}\nexport function getEditorModules(){const definitions=new Map(getModules().map(module=>[module.name,module]));return [${editEntries.join(',\n')},...sections.map(module=>({definition:definitions.get(module.name)!,Edit:(props:any)=>createElement(SchemaEditor,{...props,schema:module.schema,Component:module.Component,blockName:module.name})}))];}\n`);
|
|
27
31
|
const css=blocks.filter(folder=>fs.existsSync(path.join(root,folder,'styles.css'))).map(folder=>`@import "./${path.posix.relative('src/blocks',folder)}/styles.css";`).join('\n');
|
|
28
32
|
write(path.join(root,'src/blocks/styles.generated.css'),`/* Generated by kit. Do not edit. */\n${css}\n`);
|
|
29
33
|
const phpFile=path.join(root,'kit/generated/blocks.php');fs.mkdirSync(path.dirname(phpFile),{recursive:true});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import {prepareProject} from './prepare-project.mjs';
|
|
5
|
+
|
|
6
|
+
export function buildEditor(root, { signal }) {
|
|
7
|
+
prepareProject(root);
|
|
8
|
+
const entry=fs.existsSync(path.join(root,'scripts/build-editor.mjs'))?'scripts/build-editor.mjs':'kit/tooling/build-editor.mjs';
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const child = spawn(process.execPath, [entry], {
|
|
11
|
+
cwd: root,
|
|
12
|
+
stdio: 'inherit',
|
|
13
|
+
signal,
|
|
14
|
+
});
|
|
15
|
+
child.once('error', reject);
|
|
16
|
+
child.once('close', (code, exitSignal) => {
|
|
17
|
+
if (code === 0) resolve();
|
|
18
|
+
else reject(new Error(`Editor build exited with ${exitSignal ?? code}.`));
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Watch sources only; serialize complete JS/CSS/assets builds and recover after errors. */
|
|
24
|
+
export function watchEditor({
|
|
25
|
+
root,
|
|
26
|
+
build = (options) => buildEditor(root, options),
|
|
27
|
+
debounceMs = 150,
|
|
28
|
+
pollMs = 500,
|
|
29
|
+
log = console.log,
|
|
30
|
+
reportError = console.error,
|
|
31
|
+
}) {
|
|
32
|
+
let closed = false;
|
|
33
|
+
let pending = false;
|
|
34
|
+
let running;
|
|
35
|
+
let timer;
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const sourceDirectories = ['src', 'app', 'public', 'tools', 'scripts', 'config'];
|
|
38
|
+
const configFiles = ['tsconfig.json', 'package.json', 'kit.config.json', 'package-lock.json', '../theme.json', '../render.config.json', 'config/breakpoints.json', 'node_modules/soinproduction-gutenberg/package.json'];
|
|
39
|
+
|
|
40
|
+
// Generated kit/ is an output: watching it would rebuild forever after preparation.
|
|
41
|
+
// Poll source metadata: this also works when Next or other projects exhaust OS watchers.
|
|
42
|
+
const snapshot = () => {
|
|
43
|
+
const files = new Map();
|
|
44
|
+
const record = (file) => {
|
|
45
|
+
try {
|
|
46
|
+
const stat = fs.statSync(file, { bigint: true });
|
|
47
|
+
files.set(file, `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${stat.ino}`);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code !== 'ENOENT') throw error;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const walk = (directory) => {
|
|
53
|
+
let entries;
|
|
54
|
+
try {
|
|
55
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error.code === 'ENOENT') return;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
for (const entry of entries) {
|
|
61
|
+
if (entry.name.startsWith('.') || /(?:~|\.tmp|\.sw[op])$/.test(entry.name)) continue;
|
|
62
|
+
const file = path.join(directory, entry.name);
|
|
63
|
+
if (entry.isDirectory()) walk(file);
|
|
64
|
+
else if (entry.isFile()) record(file);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
for (const directory of sourceDirectories) walk(path.join(root, directory));
|
|
68
|
+
for (const file of configFiles) record(path.resolve(root, file));
|
|
69
|
+
return files;
|
|
70
|
+
};
|
|
71
|
+
let previous = snapshot();
|
|
72
|
+
|
|
73
|
+
const rebuild = () => {
|
|
74
|
+
if (closed || running) return running;
|
|
75
|
+
pending = false;
|
|
76
|
+
running = Promise.resolve()
|
|
77
|
+
.then(() => build({ signal: controller.signal }))
|
|
78
|
+
.then(() => {
|
|
79
|
+
if (!closed) log('[editor] Ready. Refresh WordPress to load the changes.');
|
|
80
|
+
})
|
|
81
|
+
.catch((error) => {
|
|
82
|
+
if (!closed) reportError('[editor] Build failed; watching for a fix.', error.message);
|
|
83
|
+
})
|
|
84
|
+
.finally(() => {
|
|
85
|
+
running = undefined;
|
|
86
|
+
if (pending && !closed) schedule();
|
|
87
|
+
});
|
|
88
|
+
return running;
|
|
89
|
+
};
|
|
90
|
+
const schedule = () => {
|
|
91
|
+
if (closed) return;
|
|
92
|
+
pending = true;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
timer = setTimeout(rebuild, debounceMs);
|
|
95
|
+
};
|
|
96
|
+
const interval = setInterval(() => {
|
|
97
|
+
try {
|
|
98
|
+
const current = snapshot();
|
|
99
|
+
if (
|
|
100
|
+
current.size !== previous.size ||
|
|
101
|
+
[...current].some(([file, stamp]) => previous.get(file) !== stamp)
|
|
102
|
+
)
|
|
103
|
+
schedule();
|
|
104
|
+
previous = current;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
reportError('[editor] Watch error:', error.message);
|
|
107
|
+
}
|
|
108
|
+
}, pollMs);
|
|
109
|
+
|
|
110
|
+
log('[editor] Building and watching components, styles and assets…');
|
|
111
|
+
const ready = rebuild();
|
|
112
|
+
return {
|
|
113
|
+
ready,
|
|
114
|
+
async close() {
|
|
115
|
+
closed = true;
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
clearInterval(interval);
|
|
118
|
+
controller.abort();
|
|
119
|
+
await running;
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
package/package.json
CHANGED
package/tooling/cli.mjs
CHANGED
|
@@ -1,29 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import fs from 'node:fs';
|
|
3
2
|
import path from 'node:path';
|
|
4
|
-
import {fileURLToPath} from 'node:url';
|
|
5
|
-
import {
|
|
6
|
-
import {syncKit} from './sync-kit.mjs';
|
|
7
|
-
const source=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
|
|
3
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
4
|
+
import {prepareProject} from './prepare-project.mjs';
|
|
8
5
|
const command=process.argv[2]??'help';
|
|
9
|
-
const
|
|
10
|
-
|
|
6
|
+
const input=process.argv.slice(3),args=[];
|
|
7
|
+
let root=process.cwd();
|
|
8
|
+
for(let i=0;i<input.length;i++){
|
|
9
|
+
if(input[i]==='--project'){if(!input[i+1])throw new Error('--project needs a path');root=input[++i];}
|
|
10
|
+
else if(input[i].startsWith('--project='))root=input[i].slice(10);
|
|
11
|
+
else args.push(input[i]);
|
|
12
|
+
}
|
|
13
|
+
root=path.resolve(root);
|
|
14
|
+
const noBuild=args.includes('--no-build');
|
|
15
|
+
const positional=args.filter(value=>!value.startsWith('--'));
|
|
11
16
|
if(command==='prepare'){
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
if(
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
console.log(
|
|
17
|
+
const result=prepareProject(root,{force:args.includes('--force')});
|
|
18
|
+
console.log(`Prepared kit ${result.version} in ${result.directory}`);
|
|
19
|
+
}else if(command==='dev'||command==='start'){
|
|
20
|
+
const {runDev,runStart}=await import('./dev.mjs');
|
|
21
|
+
await (command==='dev'?runDev:runStart)({root,args});
|
|
22
|
+
}else if(['build:editor','build:wordpress','build:booking'].includes(command)){
|
|
23
|
+
prepareProject(root);process.chdir(root);
|
|
24
|
+
await import(pathToFileURL(path.join(root,'kit/tooling/'+command.replace(':','-')+'.mjs')).href);
|
|
25
|
+
}else if(command==='create'||['create:component','create:section','create:layout'].includes(command)){
|
|
26
|
+
prepareProject(root);
|
|
27
|
+
const kind=command==='create'?positional[0]:command.split(':')[1];
|
|
28
|
+
const slug=command==='create'?positional[1]:positional[0];
|
|
29
|
+
const {createModule}=await import('./create-module.mjs');
|
|
30
|
+
const result=createModule(root,kind,slug,{build:!noBuild});console.log(`Created ${result.name}\n${result.directory}`);
|
|
31
|
+
}else if(command==='new:section'||(command==='new'&&positional[0]==='section')){
|
|
32
|
+
prepareProject(root);
|
|
33
|
+
const {createSection}=await import('./create-section.mjs');
|
|
34
|
+
const result=createSection(root,command==='new'?positional[1]:positional[0]);console.log(`Created ${result.name}\n${result.directory}`);
|
|
35
|
+
}else if(command==='render'||command==='render:module'){
|
|
36
|
+
prepareProject(root);
|
|
37
|
+
const {renderModule}=await import('./render-module.mjs');
|
|
38
|
+
const output=renderModule(root,positional[0],{build:!noBuild,force:args.includes('--force'),stdout:args.includes('--stdout')});
|
|
39
|
+
console.log(output);
|
|
26
40
|
}else{
|
|
27
|
-
console.log(
|
|
41
|
+
console.log(`Usage: soinproduction-kit COMMAND [--project PATH]\n\n prepare [--force]\n dev [Next options] Dynamic port and optional editor watcher\n start [Next options] Dynamic production port\n create component NAME [--no-build]\n create section NAME [--no-build] Schema-based block\n create layout NAME [--no-build]\n new section NAME Declarative kit section\n render NAME [--stdout|--force] [--no-build]\n build:editor | build:wordpress | build:booking`);
|
|
28
42
|
if(command!=='help')process.exitCode=1;
|
|
29
43
|
}
|
|
@@ -64,7 +64,7 @@ return ['id'=>'${slug}','group'=>'custom','name'=>'${name}','title'=>'${title}',
|
|
|
64
64
|
php = path.resolve(root, '../inc/blocks/registry.php'),
|
|
65
65
|
css = path.join(root, 'app/globals.css');
|
|
66
66
|
const original = new Map(
|
|
67
|
-
[registry, editor, php, css].map((f) => [f, fs.readFileSync(f, 'utf8')])
|
|
67
|
+
[registry, editor, php, css].map((f) => [f, fs.existsSync(f)?fs.readFileSync(f, 'utf8'):null])
|
|
68
68
|
);
|
|
69
69
|
try {
|
|
70
70
|
fs.mkdirSync(directory, { recursive: true });
|
|
@@ -72,9 +72,9 @@ return ['id'=>'${slug}','group'=>'custom','name'=>'${name}','title'=>'${title}',
|
|
|
72
72
|
fs.writeFileSync(path.join(directory, file), text);
|
|
73
73
|
renderModule(root, slug, { build: false });
|
|
74
74
|
syncSections(root);
|
|
75
|
-
if (build) execFileSync(
|
|
75
|
+
if (build) execFileSync(process.execPath, [path.join(root,'kit/tooling/build-editor.mjs')], { cwd: root, stdio: 'inherit' });
|
|
76
76
|
} catch (error) {
|
|
77
|
-
for (const [file, text] of original) fs.writeFileSync(file,
|
|
77
|
+
for (const [file, text] of original) {if(text===null)fs.rmSync(file,{force:true});else fs.writeFileSync(file,text);}
|
|
78
78
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
79
79
|
throw error;
|
|
80
80
|
}
|
|
@@ -1,25 +1,18 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const directory
|
|
8
|
-
if
|
|
9
|
-
const title
|
|
10
|
-
fs.mkdirSync(directory,
|
|
11
|
-
|
|
12
|
-
fs.writeFileSync(path.join(directory,
|
|
13
|
-
import meta from './section.json';
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
<Text name="text" className="mt-4" />
|
|
20
|
-
</div>
|
|
21
|
-
</Section>
|
|
22
|
-
));
|
|
23
|
-
`);
|
|
24
|
-
syncSections();
|
|
25
|
-
console.log(`Created ${directory}. Run npm run build:editor and refresh Gutenberg.`);
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {syncSections} from './sync-sections.mjs';
|
|
5
|
+
export function createSection(root,slug){
|
|
6
|
+
if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(slug??''))throw new Error('Use a lowercase name, for example consultation.');
|
|
7
|
+
const folder='section-'+slug.replace(/^section-/,''),directory=path.join(root,'src/sections',folder);
|
|
8
|
+
if(fs.existsSync(directory))throw new Error(`${folder} already exists; nothing was overwritten.`);
|
|
9
|
+
const title=slug.replace(/^section-/,'').replace(/-/g,' ').replace(/^./,c=>c.toUpperCase());
|
|
10
|
+
fs.mkdirSync(directory,{recursive:true});
|
|
11
|
+
try{
|
|
12
|
+
fs.writeFileSync(path.join(directory,'section.json'),JSON.stringify({slug:folder,title},null,2)+'\n');
|
|
13
|
+
fs.writeFileSync(path.join(directory,'section.tsx'),`import {Heading,Section,Text,section} from '@kit';\nimport meta from './section.json';\nexport default section(meta,()=> (\n <Section className="py-20">\n <div className="mx-auto max-w-7xl px-6">\n <Heading name="title" className="text-4xl"/>\n <Text name="text" className="mt-4"/>\n </div>\n </Section>\n));\n`);
|
|
14
|
+
syncSections(root);
|
|
15
|
+
}catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
16
|
+
return {directory,name:'site/'+folder};
|
|
17
|
+
}
|
|
18
|
+
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url))console.log(createSection(process.cwd(),process.argv[2]).directory);
|
package/tooling/dev.mjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {spawn} from 'node:child_process';
|
|
4
|
+
import {createRequire} from 'node:module';
|
|
5
|
+
import {prepareProject} from './prepare-project.mjs';
|
|
6
|
+
import {buildEditor,watchEditor} from './watch-editor.mjs';
|
|
7
|
+
import {nextRuntime,writeRuntime,clearRuntime} from './next-runtime.mjs';
|
|
8
|
+
|
|
9
|
+
export function renderMode(root){
|
|
10
|
+
const file=path.resolve(root,'../render.config.json');
|
|
11
|
+
const config=fs.existsSync(file)?JSON.parse(fs.readFileSync(file,'utf8')):{};
|
|
12
|
+
const mode=config.mode??'next';
|
|
13
|
+
if(!['next','wordpress'].includes(mode))throw new Error('render.config.json: mode must be next or wordpress');
|
|
14
|
+
return mode;
|
|
15
|
+
}
|
|
16
|
+
export async function runDev({root=process.cwd(),args=process.argv.slice(2),env=process.env}={}){
|
|
17
|
+
root=path.resolve(root);
|
|
18
|
+
const configFile=path.join(root,'kit.config.json');
|
|
19
|
+
const config=fs.existsSync(configFile)?JSON.parse(fs.readFileSync(configFile,'utf8')):{};
|
|
20
|
+
if(fs.existsSync(configFile))prepareProject(root);
|
|
21
|
+
const mode=renderMode(root);console.log(`[dev] Renderer: ${mode}`);
|
|
22
|
+
const editor=(config.editor?.entry||mode==='wordpress')?watchEditor({root,build:async({signal})=>{
|
|
23
|
+
await buildEditor(root,{signal});
|
|
24
|
+
if(mode==='wordpress')await new Promise((resolve,reject)=>{
|
|
25
|
+
const child=spawn(process.execPath,[path.join(root,'kit/tooling/build-wordpress.mjs')],{cwd:root,stdio:'inherit',signal});
|
|
26
|
+
child.once('error',reject);child.once('close',code=>code===0?resolve():reject(new Error('WordPress build failed')));
|
|
27
|
+
});
|
|
28
|
+
}}):{ready:Promise.resolve(),close:async()=>{}};
|
|
29
|
+
let next=null,stopping=false;
|
|
30
|
+
const stop=async(code,signal='SIGTERM')=>{
|
|
31
|
+
if(stopping)return;stopping=true;process.exitCode=code;clearRuntime(root);
|
|
32
|
+
if(next&&next.exitCode===null&&next.signalCode===null)next.kill(signal);
|
|
33
|
+
await editor.close();
|
|
34
|
+
};
|
|
35
|
+
process.once('SIGINT',()=>void stop(130,'SIGINT'));
|
|
36
|
+
process.once('SIGTERM',()=>void stop(143));
|
|
37
|
+
await editor.ready;
|
|
38
|
+
if(!stopping&&mode==='next'){
|
|
39
|
+
const runtime=await nextRuntime({args,env});
|
|
40
|
+
if(stopping)return {stop};
|
|
41
|
+
writeRuntime(root,runtime);console.log(`[dev] Frontend: ${runtime.origin}`);
|
|
42
|
+
const require=createRequire(path.join(root,'package.json'));
|
|
43
|
+
next=spawn(process.execPath,[require.resolve('next/dist/bin/next'),'dev',...runtime.args],{cwd:root,stdio:'inherit',env:runtime.env});
|
|
44
|
+
next.once('error',error=>{console.error('[dev] Could not start Next.js:',error.message);void stop(1);});
|
|
45
|
+
next.once('close',(code,signal)=>void stop(code??(signal?1:0)));
|
|
46
|
+
}
|
|
47
|
+
return {next,editor,stop};
|
|
48
|
+
}
|
|
49
|
+
export async function runStart({root=process.cwd(),args=process.argv.slice(2),env=process.env}={}){
|
|
50
|
+
root=path.resolve(root);const runtime=await nextRuntime({args,env,mode:'start'});
|
|
51
|
+
console.log(`[start] Frontend: ${runtime.origin}`);writeRuntime(root,runtime);
|
|
52
|
+
const require=createRequire(path.join(root,'package.json'));
|
|
53
|
+
const next=spawn(process.execPath,[require.resolve('next/dist/bin/next'),'start',...runtime.args],{cwd:root,stdio:'inherit',env:runtime.env});
|
|
54
|
+
const stop=signal=>{clearRuntime(root);next.kill(signal);};
|
|
55
|
+
process.once('SIGINT',()=>stop('SIGINT'));process.once('SIGTERM',()=>stop('SIGTERM'));
|
|
56
|
+
next.once('error',error=>{clearRuntime(root);console.error(error);process.exitCode=1;});
|
|
57
|
+
next.once('close',code=>{clearRuntime(root);process.exitCode=code??1;});
|
|
58
|
+
return {next,runtime,stop};
|
|
59
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import ts from 'typescript';
|
|
4
|
+
/** The distributed ESM uses .js paths; a host TS source copy must resolve TS files. */
|
|
5
|
+
export function normalizeSourceImports(directory){
|
|
6
|
+
const walk=folder=>fs.readdirSync(folder,{withFileTypes:true}).flatMap(entry=>entry.isDirectory()?walk(path.join(folder,entry.name)):[path.join(folder,entry.name)]);
|
|
7
|
+
for(const file of walk(directory).filter(file=>/\.tsx?$/.test(file))){
|
|
8
|
+
let text=fs.readFileSync(file,'utf8');
|
|
9
|
+
const source=ts.createSourceFile(file,text,ts.ScriptTarget.Latest,true),edits=[];
|
|
10
|
+
const visit=node=>{
|
|
11
|
+
let specifier;
|
|
12
|
+
if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier))specifier=node.moduleSpecifier;
|
|
13
|
+
if(ts.isCallExpression(node)&&node.expression.kind===ts.SyntaxKind.ImportKeyword&&ts.isStringLiteral(node.arguments[0]))specifier=node.arguments[0];
|
|
14
|
+
if(ts.isImportTypeNode(node)&&ts.isLiteralTypeNode(node.argument)&&ts.isStringLiteral(node.argument.literal))specifier=node.argument.literal;
|
|
15
|
+
if(specifier&&specifier.text.startsWith('.')&&specifier.text.endsWith('.js')){
|
|
16
|
+
const base=path.resolve(path.dirname(file),specifier.text.slice(0,-3));
|
|
17
|
+
if(['.ts','.tsx'].some(extension=>fs.existsSync(base+extension)))edits.push({start:specifier.getStart(source)+1,end:specifier.getEnd()-1,value:specifier.text.slice(0,-3)});
|
|
18
|
+
}
|
|
19
|
+
ts.forEachChild(node,visit);
|
|
20
|
+
};
|
|
21
|
+
visit(source);
|
|
22
|
+
for(const edit of edits.sort((a,b)=>b.start-a.start))text=text.slice(0,edit.start)+edit.value+text.slice(edit.end);
|
|
23
|
+
if(edits.length)fs.writeFileSync(file,text);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import net from 'node:net';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
function option(args,names){
|
|
6
|
+
for(let index=0;index<args.length;index++){
|
|
7
|
+
const value=args[index];
|
|
8
|
+
if(names.includes(value)){if(args[index+1]===undefined)throw new Error('Missing value for '+value);return args[index+1];}
|
|
9
|
+
for(const name of names)if(value.startsWith(name+'='))return value.slice(name.length+1);
|
|
10
|
+
if(names.includes('-p')&&/^-p\d+$/.test(value))return value.slice(2);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function withoutPort(args){
|
|
14
|
+
return args.filter((value,index)=>!['--port','-p'].includes(value)&&!['--port','-p'].includes(args[index-1])&&!/^--port=|^-p=|^-p\d+$/.test(value));
|
|
15
|
+
}
|
|
16
|
+
export function availablePort(host='0.0.0.0'){
|
|
17
|
+
return new Promise((resolve,reject)=>{
|
|
18
|
+
const server=net.createServer();server.once('error',reject);
|
|
19
|
+
server.listen({host,port:0,exclusive:true},()=>{
|
|
20
|
+
const port=server.address().port;
|
|
21
|
+
server.close(error=>error?reject(error):resolve(port));
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export async function nextRuntime({args=[],env=process.env,mode='dev',findPort=availablePort}={}){
|
|
26
|
+
const host=option(args,['--hostname','-H'])??'0.0.0.0';
|
|
27
|
+
const requested=option(args,['--port','-p'])??env.PORT;
|
|
28
|
+
if(requested!==undefined&&!/^\d+$/.test(String(requested)))throw new Error('Next port must be an integer from 0 to 65535');
|
|
29
|
+
let port=requested===undefined?0:Number(requested);
|
|
30
|
+
if(port>65535)throw new Error('Next port must be an integer from 0 to 65535');
|
|
31
|
+
if(port===0)port=await findPort(host);
|
|
32
|
+
const hostname=['0.0.0.0','::'].includes(host)?'127.0.0.1':host;
|
|
33
|
+
const protocol=args.includes('--experimental-https')?'https':'http';
|
|
34
|
+
const origin=`${protocol}://${hostname.includes(':')?'['+hostname+']':hostname}:${port}`;
|
|
35
|
+
const childEnv={...env,PORT:String(port)};
|
|
36
|
+
if(mode==='dev'){
|
|
37
|
+
childEnv.NEXT_PUBLIC_SITE_URL=origin;
|
|
38
|
+
childEnv.FORM_ENGINE_ORIGIN=origin;
|
|
39
|
+
}
|
|
40
|
+
return {args:[...withoutPort(args),'--port',String(port)],env:childEnv,port,origin};
|
|
41
|
+
}
|
|
42
|
+
export function runtimeFile(root){
|
|
43
|
+
const configFile=path.join(root,'kit.config.json');
|
|
44
|
+
const config=fs.existsSync(configFile)?JSON.parse(fs.readFileSync(configFile,'utf8')):{};
|
|
45
|
+
const value=config.runtime?.file??'build/next-server.json';
|
|
46
|
+
if(typeof value!=='string')throw new Error('runtime.file must be a project-relative path');
|
|
47
|
+
const file=path.resolve(root,value);
|
|
48
|
+
if(!file.startsWith(path.resolve(root)+path.sep))throw new Error('runtime.file must stay inside the project');
|
|
49
|
+
return file;
|
|
50
|
+
}
|
|
51
|
+
export function writeRuntime(root,runtime,pid=process.pid){
|
|
52
|
+
const file=runtimeFile(root);
|
|
53
|
+
fs.mkdirSync(path.dirname(file),{recursive:true});
|
|
54
|
+
const temporary=file+'.'+pid+'.tmp';
|
|
55
|
+
fs.writeFileSync(temporary,JSON.stringify({origin:runtime.origin,port:runtime.port,pid})+'\n');
|
|
56
|
+
fs.renameSync(temporary,file);
|
|
57
|
+
}
|
|
58
|
+
export function clearRuntime(root,pid=process.pid){
|
|
59
|
+
const file=runtimeFile(root);
|
|
60
|
+
try{if(JSON.parse(fs.readFileSync(file,'utf8')).pid===pid)fs.unlinkSync(file);}catch(error){if(error.code!=='ENOENT'&&!(error instanceof SyntaxError))console.error('[next] Could not clear runtime address:',error.message);}
|
|
61
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {syncSections} from './sync-sections.mjs';
|
|
5
|
+
import {syncKit} from './sync-kit.mjs';
|
|
6
|
+
import {normalizeSourceImports} from './materialize-source.mjs';
|
|
7
|
+
export const packageRoot=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
|
|
8
|
+
const hasFiles=folder=>fs.readdirSync(folder,{withFileTypes:true}).some(entry=>entry.isDirectory()?hasFiles(path.join(folder,entry.name)):true);
|
|
9
|
+
|
|
10
|
+
/** Keep watched source files stable; only refresh the source copy when the installed version changes. */
|
|
11
|
+
export function prepareProject(project=process.cwd(),{force=false}={}){
|
|
12
|
+
const root=path.resolve(project),destination=path.join(root,'kit'),markerFile=path.join(destination,'.kit-package.json');
|
|
13
|
+
const metadata=JSON.parse(fs.readFileSync(path.join(packageRoot,'package.json'),'utf8'));
|
|
14
|
+
let marker;try{marker=JSON.parse(fs.readFileSync(markerFile,'utf8'));}catch{}
|
|
15
|
+
const required=['index.tsx','core/fields/render.tsx','editor/seo.ts','tooling/sync-sections.mjs','tooling/sync-kit.mjs'];
|
|
16
|
+
const reusable=!force&&marker?.name===metadata.name&&marker?.version===metadata.version&&required.every(file=>fs.existsSync(path.join(destination,file)));
|
|
17
|
+
if(!reusable&&destination!==packageRoot){
|
|
18
|
+
if(fs.existsSync(destination)&&!marker&&hasFiles(destination))throw new Error('kit/ is authored source. Move it aside before preparing the npm-managed kit copy.');
|
|
19
|
+
fs.mkdirSync(destination,{recursive:true});
|
|
20
|
+
const folders=['components','editor','core','ui','admin-ui','modules','adapters','hooks','styles','schema','shared','tooling'];
|
|
21
|
+
for(const folder of folders){fs.rmSync(path.join(destination,folder),{recursive:true,force:true});fs.cpSync(path.join(packageRoot,folder),path.join(destination,folder),{recursive:true});}
|
|
22
|
+
for(const file of ['index.tsx','bootstrap.php'])fs.copyFileSync(path.join(packageRoot,file),path.join(destination,file));
|
|
23
|
+
normalizeSourceImports(destination);
|
|
24
|
+
fs.writeFileSync(markerFile,JSON.stringify({name:metadata.name,version:metadata.version},null,2)+'\n');
|
|
25
|
+
}
|
|
26
|
+
syncSections(root);syncKit(root,{directory:destination});
|
|
27
|
+
return {root,directory:destination,version:metadata.version,refreshed:!reusable};
|
|
28
|
+
}
|
|
@@ -10,19 +10,19 @@ import {buildSync} from 'esbuild';
|
|
|
10
10
|
const project = process.cwd();
|
|
11
11
|
const quote = JSON.stringify;
|
|
12
12
|
|
|
13
|
-
export function loadSchema(file) {
|
|
13
|
+
export function loadSchema(file, root = process.cwd()) {
|
|
14
14
|
const source = `import {schema} from ${quote(file)};import {validateFields} from ${quote(
|
|
15
|
-
path.join(
|
|
15
|
+
path.join(root, 'kit/core/fields/schema.ts')
|
|
16
16
|
)};export default validateFields(schema);`;
|
|
17
17
|
const result = buildSync({
|
|
18
|
-
stdin: {contents: source, resolveDir:
|
|
18
|
+
stdin: {contents: source, resolveDir: root, loader: 'ts'},
|
|
19
19
|
bundle: true,
|
|
20
20
|
write: false,
|
|
21
21
|
platform: 'node',
|
|
22
22
|
format: 'cjs',
|
|
23
23
|
packages: 'external',
|
|
24
|
-
tsconfig: path.join(
|
|
25
|
-
alias: {'@': path.join(
|
|
24
|
+
tsconfig: path.join(root, 'tsconfig.json'),
|
|
25
|
+
alias: {'@': path.join(root, 'src')},
|
|
26
26
|
});
|
|
27
27
|
const module = {exports: {}};
|
|
28
28
|
new Function('module', 'exports', 'require', result.outputFiles[0].text)(
|
|
@@ -110,7 +110,7 @@ export function renderModule(root, slug, {build = true, force = false, stdout =
|
|
|
110
110
|
throw new Error(`No schema.ts in ${slug}. Only schema-based modules support this command.`);
|
|
111
111
|
const registration = fs.readFileSync(path.join(directory, 'register.php'), 'utf8');
|
|
112
112
|
const kind = /'kind'\s*=>\s*'(component|layout)'/.exec(registration)?.[1] ?? 'section';
|
|
113
|
-
const markup = generateMarkup(loadSchema(file), slug, kind);
|
|
113
|
+
const markup = generateMarkup(loadSchema(file, root), slug, kind);
|
|
114
114
|
if (stdout) return markup;
|
|
115
115
|
const output = path.join(directory, 'component.tsx'),
|
|
116
116
|
previous = fs.existsSync(output) ? fs.readFileSync(output, 'utf8') : null;
|
|
@@ -122,7 +122,7 @@ export function renderModule(root, slug, {build = true, force = false, stdout =
|
|
|
122
122
|
);
|
|
123
123
|
try {
|
|
124
124
|
fs.writeFileSync(output, '// Generated layout sha256:' + hash(markup) + '\n' + markup);
|
|
125
|
-
if (build) execFileSync(
|
|
125
|
+
if (build) execFileSync(process.execPath, [path.join(root,'kit/tooling/build-editor.mjs')], {cwd: root, stdio: 'inherit'});
|
|
126
126
|
} catch (error) {
|
|
127
127
|
if (previous === null) fs.rmSync(output, {force: true});
|
|
128
128
|
else fs.writeFileSync(output, previous);
|
package/tooling/sync-blocks.mjs
CHANGED
|
@@ -21,9 +21,13 @@ export function syncBlocks(root=process.cwd()) {
|
|
|
21
21
|
entries.push(`defineModule({...${symbol}Info,schema:${symbol}Schema,Component:${symbol}Component})`);
|
|
22
22
|
editEntries.push(`{definition:definitions.get(${symbol}Info.name)!,Edit:${symbol}Edit}`);
|
|
23
23
|
});
|
|
24
|
+
const configFile=path.join(root,'kit.config.json');
|
|
25
|
+
const config=fs.existsSync(configFile)?JSON.parse(fs.readFileSync(configFile,'utf8')):{};
|
|
26
|
+
const content=config.adapters?.contentRenderer??(fs.existsSync(path.join(root,'src/site/rendering/native-content.tsx'))?{from:'@/site/rendering/native-content',export:'NativeContent'}:{from:'@kit/core/content/areas/render',export:'NativeAreaContent'});
|
|
27
|
+
const editor=config.adapters?.editorAdapter??(fs.existsSync(path.join(root,'src/site/editor/module-editor.tsx'))?{from:'@/site/editor/module-editor',export:'SchemaEditor'}:{from:'@kit/core/fields/editor',export:'SchemaEditor'});
|
|
24
28
|
const warning='// Generated by kit/tooling/sync-blocks.mjs. Do not edit.\n';
|
|
25
|
-
write(path.join(root,'src/blocks/registry.ts'),warning+`import {sections} from '@/sections/index.generated';\nimport {defineModule as defineCoreModule} from '@kit/core/modules/define-module';\nimport {NativeContent} from '
|
|
26
|
-
write(path.join(root,'src/blocks/editor-registry.ts'),warning+`import {createElement} from 'react';\nimport {sections} from '@/sections/index.generated';\nimport {SchemaEditor} from '
|
|
29
|
+
write(path.join(root,'src/blocks/registry.ts'),warning+`import {sections} from '@/sections/index.generated';\nimport {defineModule as defineCoreModule} from '@kit/core/modules/define-module';\nimport {${content.export} as NativeContent} from '${content.from}';\nimport type {ModuleDefinition} from '@kit/core/modules/types';\nconst defineModule=(config:Parameters<typeof defineCoreModule>[0])=>defineCoreModule({...config,Content:NativeContent});\n${imports.join('\n')}\nlet modules: ModuleDefinition[];\nexport function getModules(){return modules??=( [${entries.join(',\n')},...sections.map(module=>defineModule(module))]);}\n`);
|
|
30
|
+
write(path.join(root,'src/blocks/editor-registry.ts'),warning+`import {createElement} from 'react';\nimport {sections} from '@/sections/index.generated';\nimport {${editor.export} as SchemaEditor} from '${editor.from}';\nimport {getModules} from './registry';\n${editors.join('\n')}\nexport function getEditorModules(){const definitions=new Map(getModules().map(module=>[module.name,module]));return [${editEntries.join(',\n')},...sections.map(module=>({definition:definitions.get(module.name)!,Edit:(props:any)=>createElement(SchemaEditor,{...props,schema:module.schema,Component:module.Component,blockName:module.name})}))];}\n`);
|
|
27
31
|
const css=blocks.filter(folder=>fs.existsSync(path.join(root,folder,'styles.css'))).map(folder=>`@import "./${path.posix.relative('src/blocks',folder)}/styles.css";`).join('\n');
|
|
28
32
|
write(path.join(root,'src/blocks/styles.generated.css'),`/* Generated by kit. Do not edit. */\n${css}\n`);
|
|
29
33
|
const phpFile=path.join(root,'kit/generated/blocks.php');fs.mkdirSync(path.dirname(phpFile),{recursive:true});
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import {prepareProject} from './prepare-project.mjs';
|
|
5
|
+
|
|
6
|
+
export function buildEditor(root, { signal }) {
|
|
7
|
+
prepareProject(root);
|
|
8
|
+
const entry=fs.existsSync(path.join(root,'scripts/build-editor.mjs'))?'scripts/build-editor.mjs':'kit/tooling/build-editor.mjs';
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const child = spawn(process.execPath, [entry], {
|
|
11
|
+
cwd: root,
|
|
12
|
+
stdio: 'inherit',
|
|
13
|
+
signal,
|
|
14
|
+
});
|
|
15
|
+
child.once('error', reject);
|
|
16
|
+
child.once('close', (code, exitSignal) => {
|
|
17
|
+
if (code === 0) resolve();
|
|
18
|
+
else reject(new Error(`Editor build exited with ${exitSignal ?? code}.`));
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Watch sources only; serialize complete JS/CSS/assets builds and recover after errors. */
|
|
24
|
+
export function watchEditor({
|
|
25
|
+
root,
|
|
26
|
+
build = (options) => buildEditor(root, options),
|
|
27
|
+
debounceMs = 150,
|
|
28
|
+
pollMs = 500,
|
|
29
|
+
log = console.log,
|
|
30
|
+
reportError = console.error,
|
|
31
|
+
}) {
|
|
32
|
+
let closed = false;
|
|
33
|
+
let pending = false;
|
|
34
|
+
let running;
|
|
35
|
+
let timer;
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const sourceDirectories = ['src', 'app', 'public', 'tools', 'scripts', 'config'];
|
|
38
|
+
const configFiles = ['tsconfig.json', 'package.json', 'kit.config.json', 'package-lock.json', '../theme.json', '../render.config.json', 'config/breakpoints.json', 'node_modules/soinproduction-gutenberg/package.json'];
|
|
39
|
+
|
|
40
|
+
// Generated kit/ is an output: watching it would rebuild forever after preparation.
|
|
41
|
+
// Poll source metadata: this also works when Next or other projects exhaust OS watchers.
|
|
42
|
+
const snapshot = () => {
|
|
43
|
+
const files = new Map();
|
|
44
|
+
const record = (file) => {
|
|
45
|
+
try {
|
|
46
|
+
const stat = fs.statSync(file, { bigint: true });
|
|
47
|
+
files.set(file, `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${stat.ino}`);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code !== 'ENOENT') throw error;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const walk = (directory) => {
|
|
53
|
+
let entries;
|
|
54
|
+
try {
|
|
55
|
+
entries = fs.readdirSync(directory, { withFileTypes: true });
|
|
56
|
+
} catch (error) {
|
|
57
|
+
if (error.code === 'ENOENT') return;
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
for (const entry of entries) {
|
|
61
|
+
if (entry.name.startsWith('.') || /(?:~|\.tmp|\.sw[op])$/.test(entry.name)) continue;
|
|
62
|
+
const file = path.join(directory, entry.name);
|
|
63
|
+
if (entry.isDirectory()) walk(file);
|
|
64
|
+
else if (entry.isFile()) record(file);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
for (const directory of sourceDirectories) walk(path.join(root, directory));
|
|
68
|
+
for (const file of configFiles) record(path.resolve(root, file));
|
|
69
|
+
return files;
|
|
70
|
+
};
|
|
71
|
+
let previous = snapshot();
|
|
72
|
+
|
|
73
|
+
const rebuild = () => {
|
|
74
|
+
if (closed || running) return running;
|
|
75
|
+
pending = false;
|
|
76
|
+
running = Promise.resolve()
|
|
77
|
+
.then(() => build({ signal: controller.signal }))
|
|
78
|
+
.then(() => {
|
|
79
|
+
if (!closed) log('[editor] Ready. Refresh WordPress to load the changes.');
|
|
80
|
+
})
|
|
81
|
+
.catch((error) => {
|
|
82
|
+
if (!closed) reportError('[editor] Build failed; watching for a fix.', error.message);
|
|
83
|
+
})
|
|
84
|
+
.finally(() => {
|
|
85
|
+
running = undefined;
|
|
86
|
+
if (pending && !closed) schedule();
|
|
87
|
+
});
|
|
88
|
+
return running;
|
|
89
|
+
};
|
|
90
|
+
const schedule = () => {
|
|
91
|
+
if (closed) return;
|
|
92
|
+
pending = true;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
timer = setTimeout(rebuild, debounceMs);
|
|
95
|
+
};
|
|
96
|
+
const interval = setInterval(() => {
|
|
97
|
+
try {
|
|
98
|
+
const current = snapshot();
|
|
99
|
+
if (
|
|
100
|
+
current.size !== previous.size ||
|
|
101
|
+
[...current].some(([file, stamp]) => previous.get(file) !== stamp)
|
|
102
|
+
)
|
|
103
|
+
schedule();
|
|
104
|
+
previous = current;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
reportError('[editor] Watch error:', error.message);
|
|
107
|
+
}
|
|
108
|
+
}, pollMs);
|
|
109
|
+
|
|
110
|
+
log('[editor] Building and watching components, styles and assets…');
|
|
111
|
+
const ready = rebuild();
|
|
112
|
+
return {
|
|
113
|
+
ready,
|
|
114
|
+
async close() {
|
|
115
|
+
closed = true;
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
clearInterval(interval);
|
|
118
|
+
controller.abort();
|
|
119
|
+
await running;
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|