@bestcheckout/dynamic-component-cli 0.0.0-stage → 0.1.1

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/src/cli.mjs ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { resolve } from 'node:path';
5
+ import { initialize, createComponent } from './core/project.mjs';
6
+
7
+ const help = `Usage: dynamic-component <command> [arguments]
8
+ init <directory> --component-id <id> --page-type <checkout|upsell|downsell|thankYou>
9
+ [--cli-package <local.tgz>] Use a local package before registry distribution.
10
+ create <id> --page-type <type> [--project <directory>]
11
+ dev [--project <directory>] [--port <port>]
12
+ validate [--project <directory>] [--browser-executable <path>]
13
+ build [--project <directory>] [--component-id <id>] [--browser-executable <path>]
14
+ doctor [--project <directory>] [--port <port>] [--browser-executable <path>]
15
+ `;
16
+ try {
17
+ const { values, positionals } = parseArgs({
18
+ allowPositionals: true,
19
+ options: {
20
+ help: { type: 'boolean', short: 'h' },
21
+ version: { type: 'boolean' },
22
+ project: { type: 'string' },
23
+ 'component-id': { type: 'string' },
24
+ 'page-type': { type: 'string' },
25
+ 'cli-package': { type: 'string' },
26
+ port: { type: 'string' },
27
+ 'browser-executable': { type: 'string' },
28
+ },
29
+ });
30
+ const [command, argument, ...extra] = positionals;
31
+ if (extra.length) throw new Error('Unexpected positional arguments');
32
+ const accepted = {
33
+ init: ['component-id', 'page-type', 'cli-package'],
34
+ create: ['project', 'page-type'],
35
+ dev: ['project', 'port'],
36
+ validate: ['project', 'browser-executable'],
37
+ build: ['project', 'component-id', 'browser-executable'],
38
+ doctor: ['project', 'port', 'browser-executable'],
39
+ };
40
+ if (accepted[command] && !values.help && !values.version) {
41
+ for (const key of Object.keys(values))
42
+ if (!accepted[command].includes(key))
43
+ throw new Error(`--${key} is not supported by ${command}`);
44
+ if (argument && !['init', 'create'].includes(command))
45
+ throw new Error(`${command} does not accept positional arguments`);
46
+ }
47
+ const root = resolve(values.project || process.cwd());
48
+ if (values.version) console.log(JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version);
49
+ else if (values.help || !command) console.log(help);
50
+ else if (command === 'init') {
51
+ if (!argument) throw new Error('init requires a new directory');
52
+ await initialize(resolve(argument), values);
53
+ } else if (command === 'create') {
54
+ if (!argument) throw new Error('create requires a componentId');
55
+ await createComponent(root, argument, values['page-type'] || 'checkout');
56
+ } else if (command === 'dev') {
57
+ const { serveProject } = await import('./core/server.mjs');
58
+ const server = await serveProject(root, { port: values.port });
59
+ const close = async () => {
60
+ await server.close();
61
+ process.exit(0);
62
+ };
63
+ process.once('SIGINT', close);
64
+ process.once('SIGTERM', close);
65
+ } else if (command === 'build' || command === 'validate') {
66
+ const { validateProject } = await import('./core/validate.mjs');
67
+ await validateProject(root, {
68
+ write: command === 'build',
69
+ componentId: values['component-id'],
70
+ executablePath: values['browser-executable'],
71
+ });
72
+ } else if (command === 'doctor') {
73
+ const { diagnose } = await import('./core/doctor.mjs');
74
+ if (
75
+ !(await diagnose(root, {
76
+ port: values.port,
77
+ executablePath: values['browser-executable'],
78
+ }))
79
+ )
80
+ process.exitCode = 1;
81
+ } else throw new Error(`Unknown command: ${command}`);
82
+ } catch (error) {
83
+ console.error(
84
+ `dynamic-component: ${error instanceof Error ? error.message : String(error)}`,
85
+ );
86
+ process.exitCode = 1;
87
+ }
@@ -0,0 +1,23 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { chromium } from 'playwright';
3
+ export function browserPath(explicit) {
4
+ if (explicit) return explicit;
5
+ if (process.env.DYNAMIC_COMPONENT_BROWSER)
6
+ return process.env.DYNAMIC_COMPONENT_BROWSER;
7
+ if (existsSync(chromium.executablePath())) return undefined;
8
+ const chrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
9
+ if (process.platform === 'darwin' && existsSync(chrome)) return chrome;
10
+ return undefined;
11
+ }
12
+ export async function launchBrowser(explicit) {
13
+ try {
14
+ return await chromium.launch({
15
+ headless: true,
16
+ executablePath: browserPath(explicit),
17
+ });
18
+ } catch {
19
+ throw new Error(
20
+ 'Browser validation is unavailable. Run npx playwright install chromium, or pass --browser-executable <path>. No validation step was skipped.',
21
+ );
22
+ }
23
+ }
@@ -0,0 +1,18 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ /** Fixed tool worker only: merchant modules are transformed, never imported in Node. */
3
+ export async function runBuildWorker(workerUrl, input, { timeoutMs = 45_000 } = {}) {
4
+ const worker = new Worker(workerUrl, {workerData: input, resourceLimits: {maxOldGenerationSizeMb: 256}});
5
+ let timer;
6
+ try {
7
+ return await new Promise((resolve, reject) => {
8
+ timer = setTimeout(() => reject(Object.assign(new Error('Local build timed out. Review source and save again.'), {statusCode: 504})), timeoutMs);
9
+ worker.once('message', value => value.ok ? resolve(value.artifact) : reject(new Error(value.message)));
10
+ worker.once('error', reject);
11
+ worker.once('exit', () => reject(new Error('Local build worker stopped before returning an artifact.')));
12
+ });
13
+ } finally {
14
+ clearTimeout(timer);
15
+ // Wait for termination before releasing the single-build gate, even on timeout.
16
+ await worker.terminate();
17
+ }
18
+ }
@@ -0,0 +1,69 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ export const BUILD_SESSION_TTL_MS = 60_000;
4
+ function failure(statusCode, message) {
5
+ return Object.assign(new Error(message), { statusCode });
6
+ }
7
+ /** Process-local, single-use credentials. Never serialize this store or log headers. */
8
+ export function createBuildSessions({ now = Date.now } = {}) {
9
+ const sessions = new Map();
10
+ let windowStart = now();
11
+ let issued = 0;
12
+ let closed = false;
13
+ function prune() {
14
+ const time = now();
15
+ for (const [token, session] of sessions) if (session.expiresAt <= time) sessions.delete(token);
16
+ if (time - windowStart >= 60_000) { windowStart = time; issued = 0; }
17
+ return time;
18
+ }
19
+ return {
20
+ issue(binding) {
21
+ const time = prune();
22
+ if (closed) throw failure(503, 'Dev Server is closing');
23
+ if (sessions.size >= 64 || issued >= 120)
24
+ throw failure(429, 'Too many build sessions. Wait and retry.');
25
+ const token = randomBytes(32).toString('base64url');
26
+ const expiresAt = time + BUILD_SESSION_TTL_MS;
27
+ sessions.set(token, { sourceUrl: binding.sourceUrl, componentId: binding.componentId, expiresAt });
28
+ issued++;
29
+ return { token, expiresAt };
30
+ },
31
+ consume(authorization, binding) {
32
+ const token = typeof authorization === 'string' && /^Bearer [A-Za-z0-9_-]{43}$/.test(authorization)
33
+ ? authorization.slice(7) : '';
34
+ const time = prune();
35
+ const session = sessions.get(token);
36
+ // Any presentation consumes it, including a wrong binding or failed build.
37
+ sessions.delete(token);
38
+ if (closed || !session || session.expiresAt <= time)
39
+ throw failure(401, 'Build session is missing, expired or already used. Save again to retry.');
40
+ if (session.sourceUrl !== binding.sourceUrl || session.componentId !== binding.componentId)
41
+ throw failure(403, 'Build session does not match this source or component.');
42
+ },
43
+ close() { closed = true; sessions.clear(); },
44
+ };
45
+ }
46
+
47
+ /** Bound both the bytes and time spent waiting for a local protocol body. */
48
+ export async function readBuildInput(request, {timeoutMs = 10_000} = {}) {
49
+ let timer;
50
+ const body = (async () => {
51
+ const parts = [];
52
+ let length = 0;
53
+ for await (const part of request) {
54
+ length += part.length;
55
+ if (length > 65536) throw failure(413, 'Build request exceeds 64 KiB.');
56
+ parts.push(part);
57
+ }
58
+ return JSON.parse(Buffer.concat(parts).toString('utf8'));
59
+ })();
60
+ try {
61
+ return await Promise.race([body, new Promise((_, reject) => {
62
+ timer = setTimeout(() => {
63
+ reject(failure(408, 'Build request body timed out.'));
64
+ request.destroy();
65
+ }, timeoutMs);
66
+ timer.unref?.();
67
+ })]);
68
+ } finally { clearTimeout(timer); }
69
+ }
@@ -0,0 +1,8 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { buildSingleDynamicArtifact } from './build.mjs';
3
+ try {
4
+ const artifact = await buildSingleDynamicArtifact(workerData.sourceUrl, workerData.componentId, workerData.options);
5
+ parentPort.postMessage({ok: true, artifact});
6
+ } catch (error) {
7
+ parentPort.postMessage({ok: false, message: error instanceof Error ? error.message : 'Local build failed'});
8
+ }
@@ -0,0 +1,85 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { resolve, relative } from 'node:path';
4
+ import { build } from 'esbuild';
5
+ import { assertId, inside, safeFile, sourceFiles } from './config.mjs';
6
+ import { buildBoundary } from './source-boundary.mjs';
7
+ import { validateDynamicArtifactSource } from '../protocol/artifact.mjs';
8
+ export async function sourceFingerprint(src) {
9
+ const hash = createHash('sha256');
10
+ let size = 0;
11
+ const files = await sourceFiles(src);
12
+ if (files.length > 500) throw new Error('Source tree exceeds 500 files');
13
+ for (const file of files) {
14
+ size += (await stat(file)).size;
15
+ if (size > 16 * 1024 * 1024) throw new Error('Source tree exceeds 16 MiB');
16
+ const bytes = await readFile(file);
17
+ if (bytes.length > 16 * 1024 * 1024) throw new Error('Source file exceeds 16 MiB');
18
+ hash.update(relative(src, file)).update('\0').update(bytes).update('\0');
19
+ }
20
+ return hash.digest('hex');
21
+ }
22
+ // Shared by CLI build and Editor Local Save. Transform only; no Node import of merchant source.
23
+ export async function buildArtifact(config, component) {
24
+ assertId(component.componentId);
25
+ const entry = await safeFile(
26
+ config.src,
27
+ resolve(config.root, component.entry),
28
+ );
29
+ const before = await sourceFingerprint(config.src);
30
+ const result = await build({
31
+ absWorkingDir: config.root,
32
+ entryPoints: [entry],
33
+ bundle: true,
34
+ write: false,
35
+ format: 'esm',
36
+ platform: 'browser',
37
+ target: 'es2020',
38
+ jsx: 'automatic',
39
+ logLevel: 'silent',
40
+ tsconfigRaw: { compilerOptions: { jsx: 'react-jsx' } },
41
+ plugins: [buildBoundary(config.src)],
42
+ metafile: true,
43
+ });
44
+ if (result.outputFiles.length !== 1)
45
+ throw new Error(
46
+ 'Build must produce one JavaScript file without assets or chunks',
47
+ );
48
+ if (before !== (await sourceFingerprint(config.src)))
49
+ throw new Error('Source changed during build. Review and retry.');
50
+ const sourceText = result.outputFiles[0].text;
51
+ validateDynamicArtifactSource(sourceText);
52
+ return {
53
+ componentId: component.componentId,
54
+ fileName: component.componentId + '.js',
55
+ sourceText,
56
+ sourceHash: createHash('sha256').update(sourceText).digest('hex'),
57
+ };
58
+ }
59
+ export async function buildSingleDynamicArtifact(
60
+ sourceUrl,
61
+ componentId,
62
+ options,
63
+ ) {
64
+ assertId(componentId);
65
+ const config = options.config;
66
+ const url = new URL(sourceUrl);
67
+ if (
68
+ url.origin !== options.origin ||
69
+ url.username ||
70
+ url.password ||
71
+ url.hash ||
72
+ url.search ||
73
+ !url.pathname.startsWith('/src/')
74
+ )
75
+ throw new Error(
76
+ 'sourceUrl must point to a registered entry on this Dev Server',
77
+ );
78
+ const entry = decodeURIComponent(url.pathname.slice(1));
79
+ const component = config.components.find(
80
+ (item) => item.componentId === componentId && item.entry === entry,
81
+ );
82
+ if (!component)
83
+ throw new Error('componentId/sourceUrl does not match dynamic.config.json');
84
+ return buildArtifact(config, component);
85
+ }
@@ -0,0 +1,115 @@
1
+ import { readFile, realpath, lstat, readdir } from 'node:fs/promises';
2
+ import { isAbsolute, relative, resolve } from 'node:path';
3
+ export const idPattern = /^[a-z0-9_-]{1,64}$/;
4
+ export const pageTypes = ['checkout', 'upsell', 'downsell', 'thankYou'];
5
+ export const configName = 'dynamic.config.json';
6
+ export function inside(root, file) {
7
+ const rel = relative(root, file);
8
+ return (
9
+ rel === '' ||
10
+ (!isAbsolute(rel) &&
11
+ rel !== '..' &&
12
+ !rel.startsWith('../') &&
13
+ !rel.startsWith('..\\'))
14
+ );
15
+ }
16
+ export function assertId(id) {
17
+ if (typeof id !== 'string' || !idPattern.test(id))
18
+ throw new Error(
19
+ 'componentId must use 1–64 lowercase letters, numbers, underscores or hyphens',
20
+ );
21
+ }
22
+ export function assertPageType(type) {
23
+ if (!pageTypes.includes(type))
24
+ throw new Error(`pageType must be one of ${pageTypes.join(', ')}`);
25
+ }
26
+ export function portNumber(value) {
27
+ const port = Number(value);
28
+ if (!Number.isInteger(port) || port < 1024 || port > 65535)
29
+ throw new Error('port must be an integer from 1024 to 65535');
30
+ return port;
31
+ }
32
+ export async function safeFile(base, file) {
33
+ if (!inside(base, file)) throw new Error('Source path must stay inside src');
34
+ const actual = await realpath(file);
35
+ if (!inside(await realpath(base), actual))
36
+ throw new Error('Symlink escapes src');
37
+ return actual;
38
+ }
39
+ export async function readConfig(root, overrides = {}) {
40
+ root = await realpath(root);
41
+ const file = resolve(root, configName);
42
+ if ((await lstat(file)).isSymbolicLink())
43
+ throw new Error('Project config must not be a symlink');
44
+ const config = JSON.parse(await readFile(file, 'utf8'));
45
+ if (
46
+ config.protocolVersion !== 1 ||
47
+ !Array.isArray(config.components) ||
48
+ !config.components.length
49
+ )
50
+ throw new Error(
51
+ 'Invalid dynamic.config.json: protocolVersion=1 and components are required',
52
+ );
53
+ const ids = new Set();
54
+ const entries = new Set();
55
+ const src = resolve(root, 'src');
56
+ if ((await lstat(src)).isSymbolicLink())
57
+ throw new Error('src must not be a symlink');
58
+ for (const item of config.components) {
59
+ assertId(item.componentId);
60
+ assertPageType(item.pageType);
61
+ if (ids.has(item.componentId) || entries.has(item.entry))
62
+ throw new Error('Duplicate componentId or entry');
63
+ ids.add(item.componentId);
64
+ entries.add(item.entry);
65
+ if (
66
+ typeof item.entry !== 'string' ||
67
+ !item.entry.startsWith('src/') ||
68
+ !/\.(jsx|tsx)$/.test(item.entry)
69
+ )
70
+ throw new Error('Entry must be JSX/TSX inside src/');
71
+ await safeFile(src, resolve(root, item.entry));
72
+ }
73
+ const outDir = config.outDir || 'dist';
74
+ if (
75
+ !/^[a-zA-Z0-9_-]+$/.test(outDir) ||
76
+ ['src', 'node_modules'].includes(outDir)
77
+ )
78
+ throw new Error('outDir must be a separate project subdirectory');
79
+ try {
80
+ if ((await lstat(resolve(root, outDir))).isSymbolicLink())
81
+ throw new Error('outDir must not be a symlink');
82
+ } catch (error) {
83
+ if (error.code !== 'ENOENT') throw error;
84
+ }
85
+ return {
86
+ ...config,
87
+ root,
88
+ src,
89
+ outDir,
90
+ server: {
91
+ port: portNumber(overrides.port ?? config.server?.port ?? 5173),
92
+ },
93
+ };
94
+ }
95
+ export async function sourceFiles(directory) {
96
+ const files = [];
97
+ let entriesSeen = 0;
98
+ async function visit(dir) {
99
+ for (const item of (await readdir(dir, { withFileTypes: true })).sort(
100
+ (a, b) => a.name.localeCompare(b.name),
101
+ )) {
102
+ if (++entriesSeen > 1000) throw new Error('Source tree exceeds 1000 entries');
103
+ const file = resolve(dir, item.name);
104
+ if (item.isSymbolicLink())
105
+ throw new Error('Symlinks are not supported in component source');
106
+ if (item.isDirectory()) await visit(file);
107
+ else if (item.isFile()) {
108
+ if (files.length >= 500) throw new Error('Source tree exceeds 500 files');
109
+ files.push(file);
110
+ }
111
+ }
112
+ }
113
+ await visit(directory);
114
+ return files;
115
+ }
@@ -0,0 +1,102 @@
1
+ import { createServer } from 'node:net';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { createRequire } from 'node:module';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { readConfig } from './config.mjs';
7
+ import { launchBrowser } from './browser.mjs';
8
+ const require = createRequire(import.meta.url);
9
+ export async function diagnose(root, options = {}) {
10
+ let valid = true;
11
+ const check = async (name, callback) => {
12
+ try {
13
+ await callback();
14
+ console.log(`OK ${name}`);
15
+ } catch (error) {
16
+ valid = false;
17
+ console.error(`FAIL ${name}: ${error.message}`);
18
+ }
19
+ };
20
+ await check('Node >=20.10', () => {
21
+ const [major, minor] = process.versions.node.split('.').map(Number);
22
+ if (major < 20 || (major === 20 && minor < 10))
23
+ throw new Error('Install Node >=20.10');
24
+ });
25
+ await check('npm available', async () => {
26
+ await promisify(execFile)(
27
+ process.platform === 'win32' ? 'npm.cmd' : 'npm',
28
+ ['--version'],
29
+ { timeout: 10000 },
30
+ );
31
+ });
32
+ let config;
33
+ await check('Project config and source identity', async () => {
34
+ config = await readConfig(root, options);
35
+ });
36
+ await check('Pinned tool dependencies', async () => {
37
+ const pkg = JSON.parse(
38
+ await readFile(new URL('../../package.json', import.meta.url), 'utf8'),
39
+ );
40
+ for (const [name, expected] of Object.entries(pkg.dependencies)) {
41
+ const actual = require(`${name}/package.json`).version;
42
+ if (actual !== expected)
43
+ throw new Error(
44
+ `${name}: expected ${expected}, found ${actual}. Reinstall the CLI package.`,
45
+ );
46
+ }
47
+ });
48
+ await check('Browser validation', async () => {
49
+ const browser = await launchBrowser(options.executablePath);
50
+ await browser.close();
51
+ });
52
+ if (config) {
53
+ await check(
54
+ `Loopback port ${config.server.port} / local protocol`,
55
+ async () => {
56
+ const free = await new Promise((done, reject) => {
57
+ const socket = createServer();
58
+ socket.once('error', (error) =>
59
+ error.code === 'EADDRINUSE' ? done(false) : reject(error),
60
+ );
61
+ socket.listen(config.server.port, '127.0.0.1', () =>
62
+ socket.close(() => done(true)),
63
+ );
64
+ });
65
+ if (free) {
66
+ console.log(
67
+ 'Dev Server stopped; start npm run dev to verify metadata/build/HMR through the Editor.',
68
+ );
69
+ return;
70
+ }
71
+ const origin = `http://127.0.0.1:${config.server.port}`;
72
+ let meta;
73
+ try {
74
+ const response = await fetch(origin + '/.well-known/dynamic.json', {
75
+ signal: AbortSignal.timeout(3000),
76
+ });
77
+ if (!response.ok) throw new Error();
78
+ meta = await response.json();
79
+ } catch {
80
+ throw new Error(
81
+ 'Port is occupied by an incompatible/unavailable server. Stop it or choose --port.',
82
+ );
83
+ }
84
+ if (
85
+ meta.protocolVersion !== 1 ||
86
+ meta.build?.url !== origin + '/.well-known/dynamic-build' ||
87
+ meta.hmr?.transport !== 'websocket'
88
+ )
89
+ throw new Error(
90
+ 'Running Dev Server metadata is incompatible. Restart the CLI Dev Server.',
91
+ );
92
+ console.log(
93
+ 'Running metadata declares build and WebSocket HMR; no build was triggered by doctor.',
94
+ );
95
+ },
96
+ );
97
+ }
98
+ console.log(
99
+ 'Browser HTTPS/local-network permission and production compatibility require Editor acceptance; doctor cannot grant or prove those permissions.',
100
+ );
101
+ return valid;
102
+ }
@@ -0,0 +1,143 @@
1
+ import {
2
+ readFile,
3
+ writeFile,
4
+ mkdir,
5
+ readdir,
6
+ cp,
7
+ copyFile,
8
+ lstat,
9
+ } from 'node:fs/promises';
10
+ import { dirname, resolve, join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { assertId, assertPageType, readConfig, configName } from './config.mjs';
13
+ const packageRoot = fileURLToPath(new URL('../../', import.meta.url));
14
+ export function componentSource(id, pageType) {
15
+ const capability = ['upsell', 'downsell'].includes(pageType)
16
+ ? ', capabilities: { offerRecommendation: true }'
17
+ : '';
18
+ return `import { useSyncExternalStore } from "react";
19
+ import type { DynamicComponentDefinition, DynamicComponentProps } from "@bestcheckout/dynamic-component-cli/types";
20
+
21
+ export const manifest = { componentId: ${JSON.stringify(id)}, name: ${JSON.stringify(id)}, supportedPageTypes: [${JSON.stringify(pageType)}] as const${capability} };
22
+ export const schema = [{ key: "heading", type: "text", label: "Heading" }];
23
+ export const defaultSettings = { heading: "My dynamic component" };
24
+ export const styles = ".example{padding:20px;border:1px solid #ddd;border-radius:8px}";
25
+ export function Component({ settings, runtime }: DynamicComponentProps) {
26
+ // Host supplies business data. Missing capabilities remain unavailable.
27
+ const account = runtime.account;
28
+ const snapshot = useSyncExternalStore(account ? listener => account.subscribe(() => listener()) : () => () => {}, account ? () => account.getSnapshot() : () => undefined);
29
+ return <section className="example"><h2>{String(settings.heading || "")}</h2><p>Page: {runtime.page.pageType}</p><p>Account: {snapshot?.status || "unavailable"}</p></section>;
30
+ }
31
+ export default { manifest, schema, defaultSettings, styles, Component } satisfies DynamicComponentDefinition;
32
+ `;
33
+ }
34
+ export async function initialize(target, options) {
35
+ const id = options['component-id'] || 'my-component';
36
+ const pageType = options['page-type'] || 'checkout';
37
+ assertId(id);
38
+ assertPageType(pageType);
39
+ try {
40
+ if ((await lstat(target)).isSymbolicLink())
41
+ throw new Error('Target must not be a symlink');
42
+ if ((await readdir(target)).length)
43
+ throw new Error(`Directory is not empty: ${target}`);
44
+ } catch (error) {
45
+ if (error.code !== 'ENOENT') throw error;
46
+ }
47
+ const pkg = JSON.parse(
48
+ await readFile(join(packageRoot, 'package.json'), 'utf8'),
49
+ );
50
+ let cliDependency = pkg.version;
51
+ if (options['cli-package']) {
52
+ const source = resolve(options['cli-package']);
53
+ if (!source.endsWith('.tgz') || !(await lstat(source)).isFile())
54
+ throw new Error('--cli-package must point to an npm .tgz archive');
55
+ await mkdir(join(target, 'vendor'), { recursive: true });
56
+ await copyFile(source, join(target, 'vendor', 'dynamic-component-cli.tgz'));
57
+ cliDependency = 'file:vendor/dynamic-component-cli.tgz';
58
+ }
59
+ await mkdir(join(target, 'src', id), { recursive: true });
60
+ const templates = join(packageRoot, 'templates', 'starter');
61
+ for (const name of await readdir(templates))
62
+ await cp(join(templates, name), join(target, name), {
63
+ recursive: true,
64
+ errorOnExist: true,
65
+ force: false,
66
+ });
67
+ await writeFile(
68
+ join(target, '.gitignore'),
69
+ 'node_modules/\ndist/\n.dynamic-cache/\n',
70
+ );
71
+ await writeFile(
72
+ join(target, 'package.json'),
73
+ JSON.stringify(
74
+ {
75
+ name: 'dynamic-component-project',
76
+ version: '0.1.0',
77
+ private: true,
78
+ type: 'module',
79
+ scripts: {
80
+ dev: 'dynamic-component dev',
81
+ validate: 'dynamic-component validate',
82
+ build: 'dynamic-component build',
83
+ doctor: 'dynamic-component doctor',
84
+ },
85
+ dependencies: { react: '18.3.1', 'react-dom': '18.3.1' },
86
+ devDependencies: {
87
+ [pkg.name]: cliDependency,
88
+ '@types/react': '18.3.12',
89
+ '@types/react-dom': '18.3.1',
90
+ },
91
+ },
92
+ null,
93
+ 2,
94
+ ) + '\n',
95
+ );
96
+ await writeFile(
97
+ join(target, configName),
98
+ JSON.stringify(
99
+ {
100
+ protocolVersion: 1,
101
+ components: [
102
+ { componentId: id, pageType, entry: `src/${id}/component.tsx` },
103
+ ],
104
+ server: {
105
+ port: 5173,
106
+ },
107
+ outDir: 'dist',
108
+ },
109
+ null,
110
+ 2,
111
+ ) + '\n',
112
+ );
113
+ await writeFile(
114
+ join(target, 'src', id, 'component.tsx'),
115
+ componentSource(id, pageType),
116
+ { flag: 'wx' },
117
+ );
118
+ console.log(
119
+ `Initialized ${target}\nNext: cd into that directory, npm install, npm run dev; npm run build validates and writes artifacts`,
120
+ );
121
+ }
122
+ export async function createComponent(root, id, pageType) {
123
+ assertId(id);
124
+ assertPageType(pageType);
125
+ const config = await readConfig(root);
126
+ if (config.components.some((item) => item.componentId === id))
127
+ throw new Error('Component already exists');
128
+ const target = join(config.src, id);
129
+ await mkdir(target); // EEXIST is intentional: never overwrite a directory or symlink.
130
+ await writeFile(
131
+ join(target, 'component.tsx'),
132
+ componentSource(id, pageType),
133
+ { flag: 'wx' },
134
+ );
135
+ const raw = JSON.parse(await readFile(join(root, configName), 'utf8'));
136
+ raw.components.push({
137
+ componentId: id,
138
+ pageType,
139
+ entry: `src/${id}/component.tsx`,
140
+ });
141
+ await writeFile(join(root, configName), JSON.stringify(raw, null, 2) + '\n');
142
+ console.log(`Created ${id}`);
143
+ }