@bestcheckout/dynamic-component-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +147 -2
- package/package.json +51 -4
- package/src/cli.mjs +87 -0
- package/src/core/browser.mjs +23 -0
- package/src/core/build-runner.mjs +18 -0
- package/src/core/build-session.mjs +69 -0
- package/src/core/build-worker.mjs +8 -0
- package/src/core/build.mjs +85 -0
- package/src/core/config.mjs +115 -0
- package/src/core/doctor.mjs +102 -0
- package/src/core/project.mjs +143 -0
- package/src/core/react-bridge.mjs +65 -0
- package/src/core/server.mjs +191 -0
- package/src/core/source-boundary.mjs +69 -0
- package/src/core/validate.mjs +247 -0
- package/src/protocol/artifact.mjs +88 -0
- package/src/protocol/validation.mjs +96 -0
- package/templates/starter/README.md +56 -0
- package/templates/starter/tsconfig.json +14 -0
- package/types/index.d.ts +1230 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Development modules use the same Host bridge as uploaded artifacts. Keep
|
|
2
|
+
// this in the Dev Server adapter: merchant components still import React normally.
|
|
3
|
+
const modules = {
|
|
4
|
+
react: ['react', ['Children', 'Component', 'Fragment', 'Profiler', 'PureComponent', 'StrictMode', 'Suspense', 'cloneElement', 'createContext', 'createElement', 'createFactory', 'createRef', 'forwardRef', 'isValidElement', 'lazy', 'memo', 'startTransition', 'useCallback', 'useContext', 'useDebugValue', 'useDeferredValue', 'useEffect', 'useId', 'useImperativeHandle', 'useInsertionEffect', 'useLayoutEffect', 'useMemo', 'useReducer', 'useRef', 'useState', 'useSyncExternalStore', 'useTransition', 'version']],
|
|
5
|
+
'react-dom': ['reactDom', ['createPortal', 'flushSync', 'findDOMNode', 'hydrate', 'render', 'unmountComponentAtNode']],
|
|
6
|
+
'react-dom/client': ['reactDomClient', ['createRoot', 'hydrateRoot']],
|
|
7
|
+
'react/jsx-runtime': ['jsxRuntime', ['Fragment', 'jsx', 'jsxs']],
|
|
8
|
+
'react/jsx-dev-runtime': ['jsxDevRuntime', ['Fragment', 'jsxDEV']],
|
|
9
|
+
};
|
|
10
|
+
const prefix = '\0shop-visual-host-runtime:';
|
|
11
|
+
|
|
12
|
+
export function hostReactRuntime() {
|
|
13
|
+
return {
|
|
14
|
+
name: 'shop-visual-host-react-runtime',
|
|
15
|
+
apply: 'serve',
|
|
16
|
+
enforce: 'pre',
|
|
17
|
+
config() {
|
|
18
|
+
// Prevent dependency prebundling from embedding a separate React copy,
|
|
19
|
+
// including imports originating in other dependencies.
|
|
20
|
+
return { optimizeDeps: { exclude: Object.keys(modules) } };
|
|
21
|
+
},
|
|
22
|
+
configResolved(config) {
|
|
23
|
+
// @vitejs/plugin-react adds React to include during config merging. It
|
|
24
|
+
// must not be both an optimizer entry and an external dependency.
|
|
25
|
+
config.optimizeDeps.include = (config.optimizeDeps.include ?? []).filter(name => !Object.hasOwn(modules, name));
|
|
26
|
+
},
|
|
27
|
+
configureServer(server) {
|
|
28
|
+
server.middlewares.use((request, response, next) => {
|
|
29
|
+
const end = response.end.bind(response);
|
|
30
|
+
response.end = (chunk, ...args) => {
|
|
31
|
+
if ((typeof chunk === 'string' || Buffer.isBuffer(chunk)) && String(response.getHeader('Content-Type')).includes('javascript')) {
|
|
32
|
+
// The Host can import fetched entry bytes through a Blob URL. A
|
|
33
|
+
// root-relative virtual module would have no base in that case.
|
|
34
|
+
const origin = `${server.config.server.https ? 'https' : 'http'}://${request.headers.host}`;
|
|
35
|
+
const source = Buffer.from(chunk).toString('utf8').replace(
|
|
36
|
+
/(["'])\/@id\/__x00__shop-visual-host-runtime:([^"']+)\1/g,
|
|
37
|
+
(_match, quote, name) => `${quote}${origin}/@id/__x00__shop-visual-host-runtime:${name}${quote}`,
|
|
38
|
+
);
|
|
39
|
+
response.setHeader('Content-Length', Buffer.byteLength(source));
|
|
40
|
+
return end(Buffer.from(source), ...args);
|
|
41
|
+
}
|
|
42
|
+
return end(chunk, ...args);
|
|
43
|
+
};
|
|
44
|
+
next();
|
|
45
|
+
});
|
|
46
|
+
},
|
|
47
|
+
resolveId(source) {
|
|
48
|
+
if (Object.hasOwn(modules, source)) return prefix + source;
|
|
49
|
+
if (/^react(?:-dom)?\//.test(source)) {
|
|
50
|
+
throw new Error(`Unsupported Host React runtime import: ${source}`);
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
load(id) {
|
|
54
|
+
if (!id.startsWith(prefix)) return;
|
|
55
|
+
const specifier = id.slice(prefix.length);
|
|
56
|
+
const [key, names] = modules[specifier];
|
|
57
|
+
return [
|
|
58
|
+
`const runtime = globalThis.__SHOP_VISUAL_DYNAMIC_RUNTIME__?.[${JSON.stringify(key)}];`,
|
|
59
|
+
`if (!runtime) throw new Error(${JSON.stringify(`Host React runtime is unavailable for ${specifier}. Open this component through the theme editor Local Dev Server preview.`)});`,
|
|
60
|
+
'export default runtime;',
|
|
61
|
+
...names.map(name => `export const ${name} = runtime.${name};`),
|
|
62
|
+
].join('\n');
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createServer } from 'vite';
|
|
2
|
+
import { createBuildSessions, readBuildInput } from './build-session.mjs';
|
|
3
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
4
|
+
import { resolve, relative } from 'node:path';
|
|
5
|
+
import { readConfig, inside } from './config.mjs';
|
|
6
|
+
import { hostReactRuntime } from './react-bridge.mjs';
|
|
7
|
+
import { sourceBoundary } from './source-boundary.mjs';
|
|
8
|
+
import { runBuildWorker } from './build-runner.mjs';
|
|
9
|
+
|
|
10
|
+
function json(response, status, body) {
|
|
11
|
+
response.statusCode = status;
|
|
12
|
+
response.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
13
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
14
|
+
response.end(JSON.stringify(body));
|
|
15
|
+
}
|
|
16
|
+
export async function serveProject(root, options = {}) {
|
|
17
|
+
const config = await readConfig(root, options);
|
|
18
|
+
const port = config.server.port;
|
|
19
|
+
const origin = `http://127.0.0.1:${port}`;
|
|
20
|
+
const canonicalBuildInput = (input) => {
|
|
21
|
+
if (!input || typeof input.sourceUrl !== 'string' || typeof input.componentId !== 'string')
|
|
22
|
+
throw new Error('sourceUrl and componentId are required');
|
|
23
|
+
const url = new URL(input.sourceUrl);
|
|
24
|
+
if (url.origin !== origin && url.origin !== `http://localhost:${port}`)
|
|
25
|
+
throw new Error('sourceUrl origin does not match this Dev Server');
|
|
26
|
+
if (url.username || url.password || url.hash || url.search || !url.pathname.startsWith('/src/'))
|
|
27
|
+
throw new Error('sourceUrl must point to a registered entry on this Dev Server');
|
|
28
|
+
const entry = decodeURIComponent(url.pathname.slice(1));
|
|
29
|
+
const component = config.components.find(item => item.componentId === input.componentId && item.entry === entry);
|
|
30
|
+
if (!component) throw new Error('componentId/sourceUrl does not match dynamic.config.json');
|
|
31
|
+
return { sourceUrl: url.href, componentId: input.componentId };
|
|
32
|
+
};
|
|
33
|
+
const plugin = {
|
|
34
|
+
name: 'dynamic-component-http',
|
|
35
|
+
enforce: 'pre',
|
|
36
|
+
configureServer(server) {
|
|
37
|
+
let busy = false;
|
|
38
|
+
const buildSessions = createBuildSessions();
|
|
39
|
+
server.httpServer?.once('close', () => buildSessions.close());
|
|
40
|
+
server.middlewares.use(async (request, response, next) => {
|
|
41
|
+
const host = request.headers.host;
|
|
42
|
+
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(host))
|
|
43
|
+
return json(response, 403, { message: 'Invalid Dev Server Host' });
|
|
44
|
+
response.setHeader('Access-Control-Allow-Origin', '*');
|
|
45
|
+
response.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
|
|
46
|
+
response.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
47
|
+
if (request.method === 'OPTIONS') {
|
|
48
|
+
response.statusCode = 204;
|
|
49
|
+
response.end();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const url = new URL(request.url || '/', origin);
|
|
54
|
+
const path = decodeURIComponent(url.pathname);
|
|
55
|
+
if (path.startsWith('/.well-known/') && url.search)
|
|
56
|
+
return json(response, 400, { message: 'Protocol query is not permitted' });
|
|
57
|
+
if (path === '/.well-known/dynamic.json') {
|
|
58
|
+
if (request.method !== 'GET')
|
|
59
|
+
return json(response, 405, { message: 'GET is required' });
|
|
60
|
+
return json(response, 200, {
|
|
61
|
+
protocolVersion: 1,
|
|
62
|
+
build: { url: origin + '/.well-known/dynamic-build' },
|
|
63
|
+
buildSession: { url: origin + '/.well-known/dynamic-build-session' },
|
|
64
|
+
hmr: {
|
|
65
|
+
transport: 'websocket',
|
|
66
|
+
url: `ws://127.0.0.1:${port}/`,
|
|
67
|
+
protocol: 'vite-hmr',
|
|
68
|
+
token: server.config.webSocketToken,
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (path === '/.well-known/dynamic-build-session') {
|
|
73
|
+
if (request.method !== 'POST') return json(response, 405, { message: 'POST is required' });
|
|
74
|
+
if (!request.headers['content-type']?.startsWith('application/json'))
|
|
75
|
+
return json(response, 403, { message: 'application/json is required' });
|
|
76
|
+
const input = canonicalBuildInput(await readBuildInput(request));
|
|
77
|
+
return json(response, 200, buildSessions.issue(input));
|
|
78
|
+
}
|
|
79
|
+
if (path === '/.well-known/dynamic-build') {
|
|
80
|
+
if (request.method !== 'POST')
|
|
81
|
+
return json(response, 405, { message: 'POST is required' });
|
|
82
|
+
if (
|
|
83
|
+
!request.headers['content-type']?.startsWith('application/json')
|
|
84
|
+
)
|
|
85
|
+
return json(response, 403, {
|
|
86
|
+
message:
|
|
87
|
+
'application/json is required',
|
|
88
|
+
});
|
|
89
|
+
const input = canonicalBuildInput(await readBuildInput(request));
|
|
90
|
+
buildSessions.consume(request.headers.authorization, input);
|
|
91
|
+
if (busy) return json(response, 409, { message: 'A local build is already running. Save again after it completes.' });
|
|
92
|
+
busy = true;
|
|
93
|
+
try {
|
|
94
|
+
return json(response, 200, await runBuildWorker(new URL('./build-worker.mjs', import.meta.url), {
|
|
95
|
+
...input, options: { config, origin: new URL(input.sourceUrl).origin },
|
|
96
|
+
}));
|
|
97
|
+
} finally { busy = false; }
|
|
98
|
+
}
|
|
99
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
100
|
+
return json(response, 405, { message: 'Read-only route' });
|
|
101
|
+
if (
|
|
102
|
+
['/@vite/client', '/@vite/env'].includes(path) ||
|
|
103
|
+
path.startsWith('/@id/__x00__shop-visual-host-runtime:')
|
|
104
|
+
)
|
|
105
|
+
return next();
|
|
106
|
+
if (path.startsWith('/src/')) {
|
|
107
|
+
const file = await realpath(resolve(root, '.' + path));
|
|
108
|
+
if (
|
|
109
|
+
!inside(config.src, file) ||
|
|
110
|
+
/(?:^|[/\\])\./.test(path) ||
|
|
111
|
+
/(?:^|[/\\])\./.test(relative(config.src, file)) ||
|
|
112
|
+
!/\.(?:[cm]?[jt]sx?|json)$/.test(file) ||
|
|
113
|
+
[...url.searchParams.keys()].some(
|
|
114
|
+
(key) => !['t', 'import', 'v', '__ve_hmr'].includes(key),
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
return json(response, 403, {
|
|
118
|
+
message: 'Source path is not permitted',
|
|
119
|
+
});
|
|
120
|
+
return next();
|
|
121
|
+
}
|
|
122
|
+
if (
|
|
123
|
+
path.startsWith(`/${config.outDir}/`) &&
|
|
124
|
+
/^[a-z0-9_-]+\.js$/.test(path.slice(config.outDir.length + 2))
|
|
125
|
+
) {
|
|
126
|
+
const dir = resolve(root, config.outDir);
|
|
127
|
+
const file = await realpath(resolve(root, '.' + path));
|
|
128
|
+
if (!inside(dir, file))
|
|
129
|
+
return json(response, 403, {
|
|
130
|
+
message: 'Artifact path is not permitted',
|
|
131
|
+
});
|
|
132
|
+
response.setHeader(
|
|
133
|
+
'Content-Type',
|
|
134
|
+
'text/javascript; charset=utf-8',
|
|
135
|
+
);
|
|
136
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
137
|
+
response.end(await readFile(file));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
return json(response, 404, {
|
|
141
|
+
message:
|
|
142
|
+
'Only registered component source, build metadata and artifacts are served',
|
|
143
|
+
});
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (response.destroyed) return;
|
|
146
|
+
return json(response, error.statusCode || (error.code === 'ENOENT' ? 404 : 400), {
|
|
147
|
+
message:
|
|
148
|
+
error instanceof Error ? error.message : 'Local request failed',
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
const server = await createServer({
|
|
155
|
+
configFile: false,
|
|
156
|
+
root,
|
|
157
|
+
publicDir: false,
|
|
158
|
+
envFile: false,
|
|
159
|
+
cacheDir: resolve(root, '.dynamic-cache'),
|
|
160
|
+
base: origin + '/',
|
|
161
|
+
logLevel: 'warn',
|
|
162
|
+
plugins: [plugin, hostReactRuntime(), sourceBoundary(config.src)],
|
|
163
|
+
esbuild: { jsx: 'automatic' },
|
|
164
|
+
optimizeDeps: { noDiscovery: true },
|
|
165
|
+
server: {
|
|
166
|
+
host: '127.0.0.1',
|
|
167
|
+
port,
|
|
168
|
+
strictPort: true,
|
|
169
|
+
origin,
|
|
170
|
+
cors: true,
|
|
171
|
+
fs: { strict: true, allow: [config.src] },
|
|
172
|
+
hmr: { host: '127.0.0.1', port },
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
try {
|
|
176
|
+
await server.listen();
|
|
177
|
+
} catch (error) {
|
|
178
|
+
await server.close();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
if (!options.quiet) {
|
|
182
|
+
for (const item of config.components)
|
|
183
|
+
console.log(
|
|
184
|
+
`${item.componentId} (${item.pageType}): ${origin}/${item.entry}`,
|
|
185
|
+
);
|
|
186
|
+
console.log(
|
|
187
|
+
`Metadata: ${origin}/.well-known/dynamic.json\nConnect a Local URL in the Editor. Ctrl+C stops this server.`,
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
return server;
|
|
191
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
3
|
+
import { inside } from './config.mjs';
|
|
4
|
+
const allowedImports = new Set([
|
|
5
|
+
'react',
|
|
6
|
+
'react-dom',
|
|
7
|
+
'react-dom/client',
|
|
8
|
+
'react/jsx-runtime',
|
|
9
|
+
'react/jsx-dev-runtime',
|
|
10
|
+
]);
|
|
11
|
+
export function assertPublicImport(specifier) {
|
|
12
|
+
if (allowedImports.has(specifier)) return;
|
|
13
|
+
if (!specifier.startsWith('./') && !specifier.startsWith('../'))
|
|
14
|
+
throw new Error(
|
|
15
|
+
`Unsupported dependency: ${specifier}. Only local source and platform React imports are supported.`,
|
|
16
|
+
);
|
|
17
|
+
if (
|
|
18
|
+
/[?#]/.test(specifier) ||
|
|
19
|
+
/\.(css|less|scss|sass|svg|png|jpe?g|gif|webp)$/i.test(specifier)
|
|
20
|
+
)
|
|
21
|
+
throw new Error(
|
|
22
|
+
'Use exported styles and hosted asset URLs; asset/CSS imports are not single-file components',
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
export function sourceBoundary(sourceDirectory) {
|
|
26
|
+
const root = realpathSync(sourceDirectory);
|
|
27
|
+
return {
|
|
28
|
+
name: 'dynamic-component-source-boundary',
|
|
29
|
+
enforce: 'pre',
|
|
30
|
+
async resolveId(source, importer) {
|
|
31
|
+
if (
|
|
32
|
+
!importer ||
|
|
33
|
+
importer.startsWith('\0') ||
|
|
34
|
+
!inside(root, importer.split('?')[0])
|
|
35
|
+
)
|
|
36
|
+
return;
|
|
37
|
+
assertPublicImport(source);
|
|
38
|
+
const result = await this.resolve(source, importer, { skipSelf: true });
|
|
39
|
+
if (result && !result.external && !result.id.startsWith('\0')) {
|
|
40
|
+
const clean = result.id.split('?')[0];
|
|
41
|
+
if (
|
|
42
|
+
isAbsolute(clean) &&
|
|
43
|
+
!allowedImports.has(source) &&
|
|
44
|
+
!inside(root, realpathSync(clean))
|
|
45
|
+
)
|
|
46
|
+
throw new Error('Resolved dependency escapes src');
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export function buildBoundary(sourceDirectory) {
|
|
53
|
+
const root = realpathSync(sourceDirectory);
|
|
54
|
+
return {
|
|
55
|
+
name: 'dynamic-component-source-boundary',
|
|
56
|
+
setup(build) {
|
|
57
|
+
build.onResolve({ filter: /.*/ }, (args) => {
|
|
58
|
+
if (args.kind === 'entry-point') return;
|
|
59
|
+
assertPublicImport(args.path);
|
|
60
|
+
if (allowedImports.has(args.path))
|
|
61
|
+
return { path: args.path, external: true };
|
|
62
|
+
});
|
|
63
|
+
build.onLoad({ filter: /./ }, (args) => {
|
|
64
|
+
if (!inside(root, realpathSync(args.path)))
|
|
65
|
+
throw new Error('Resolved dependency escapes src');
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|