@blocklet/pages-kit-runtime 0.1.2 → 0.1.5
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/lib/cjs/tsconfig.tsbuildinfo +1 -1
- package/lib/esm/tsconfig.tsbuildinfo +1 -1
- package/lib/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +3 -35
- package/lib/cjs/block-studio/build-lib.js +0 -95
- package/lib/cjs/block-studio/generate-wrapper-code.js +0 -123
- package/lib/cjs/block-studio/init-resource-router.js +0 -166
- package/lib/cjs/block-studio/plugins/_theme.js +0 -7
- package/lib/cjs/block-studio/plugins/index.js +0 -19
- package/lib/cjs/block-studio/plugins/vite-plugin-block-studio.js +0 -176
- package/lib/cjs/block-studio/plugins/vite-plugin-html-transform.js +0 -245
- package/lib/cjs/block-studio/plugins/vite-plugin-remote-script-localizer.js +0 -211
- package/lib/cjs/block-studio/utils.js +0 -53
- package/lib/esm/block-studio/build-lib.js +0 -89
- package/lib/esm/block-studio/generate-wrapper-code.js +0 -87
- package/lib/esm/block-studio/init-resource-router.js +0 -124
- package/lib/esm/block-studio/plugins/_theme.js +0 -4
- package/lib/esm/block-studio/plugins/index.js +0 -3
- package/lib/esm/block-studio/plugins/vite-plugin-block-studio.js +0 -140
- package/lib/esm/block-studio/plugins/vite-plugin-html-transform.js +0 -241
- package/lib/esm/block-studio/plugins/vite-plugin-remote-script-localizer.js +0 -175
- package/lib/esm/block-studio/utils.js +0 -43
- package/lib/types/block-studio/build-lib.d.ts +0 -3
- package/lib/types/block-studio/generate-wrapper-code.d.ts +0 -5
- package/lib/types/block-studio/init-resource-router.d.ts +0 -5
- package/lib/types/block-studio/plugins/_theme.d.ts +0 -1
- package/lib/types/block-studio/plugins/index.d.ts +0 -3
- package/lib/types/block-studio/plugins/vite-plugin-block-studio.d.ts +0 -6
- package/lib/types/block-studio/plugins/vite-plugin-html-transform.d.ts +0 -5
- package/lib/types/block-studio/plugins/vite-plugin-remote-script-localizer.d.ts +0 -8
- package/lib/types/block-studio/utils.d.ts +0 -14
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
export function generateWrapperCode(_a) {
|
|
11
|
-
return __awaiter(this, arguments, void 0, function* ({ project, state }) {
|
|
12
|
-
const projectName = (project.name || project.id).toLowerCase().replaceAll(/[^a-z0-9]/g, '_');
|
|
13
|
-
const packageName = `@pages-kit-project/${projectName}`;
|
|
14
|
-
const packageJson = JSON.stringify({
|
|
15
|
-
name: packageName,
|
|
16
|
-
version: '0.0.1',
|
|
17
|
-
main: 'index.cjs',
|
|
18
|
-
module: 'index.js',
|
|
19
|
-
types: 'index.d.ts',
|
|
20
|
-
peerDependencies: {
|
|
21
|
-
'@blocklet/pages-kit-runtime': 'latest',
|
|
22
|
-
},
|
|
23
|
-
dependencies: {
|
|
24
|
-
'@blocklet/pages-kit-runtime': 'latest',
|
|
25
|
-
'@blocklet/pages-kit': 'latest',
|
|
26
|
-
},
|
|
27
|
-
exports: {
|
|
28
|
-
'.': {
|
|
29
|
-
require: './index.cjs',
|
|
30
|
-
import: './index.js',
|
|
31
|
-
types: './index.d.ts',
|
|
32
|
-
},
|
|
33
|
-
'./client': {
|
|
34
|
-
require: './client.cjs',
|
|
35
|
-
import: './client.js',
|
|
36
|
-
types: './client.d.ts',
|
|
37
|
-
},
|
|
38
|
-
},
|
|
39
|
-
}, null, 2);
|
|
40
|
-
const index = `\
|
|
41
|
-
import { ProjectRuntime } from '@blocklet/pages-kit-runtime/client';
|
|
42
|
-
|
|
43
|
-
window.__PAGE_STATE__ = ${JSON.stringify(state, null, 2)};
|
|
44
|
-
window.__PROJECT_ID__ = "${project.id}";
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const ${projectName} = new ProjectRuntime({
|
|
48
|
-
state: window.__PAGE_STATE__,
|
|
49
|
-
projectId: window.__PROJECT_ID__,
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
export default ${projectName}
|
|
53
|
-
`;
|
|
54
|
-
const client = index;
|
|
55
|
-
const tsFiles = [
|
|
56
|
-
{ fileName: 'index.ts', content: index },
|
|
57
|
-
{ fileName: 'client.ts', content: client },
|
|
58
|
-
];
|
|
59
|
-
const ts = yield import('typescript');
|
|
60
|
-
const result = (yield Promise.all(tsFiles.map((_a) => __awaiter(this, [_a], void 0, function* ({ fileName, content }) {
|
|
61
|
-
const cjs = ts.transpileModule(content, {
|
|
62
|
-
fileName,
|
|
63
|
-
compilerOptions: { module: ts.ModuleKind.CommonJS },
|
|
64
|
-
});
|
|
65
|
-
const esm = ts.transpileModule(content, {
|
|
66
|
-
fileName,
|
|
67
|
-
compilerOptions: { module: ts.ModuleKind.ESNext },
|
|
68
|
-
});
|
|
69
|
-
return [
|
|
70
|
-
{
|
|
71
|
-
fileName: fileName.replace(/\.ts$/, '.cjs'),
|
|
72
|
-
content: cjs.outputText,
|
|
73
|
-
},
|
|
74
|
-
{
|
|
75
|
-
fileName: fileName.replace(/\.ts$/, '.js'),
|
|
76
|
-
content: esm.outputText,
|
|
77
|
-
},
|
|
78
|
-
{
|
|
79
|
-
fileName: fileName.replace(/\.ts$/, '.d.ts'),
|
|
80
|
-
content,
|
|
81
|
-
},
|
|
82
|
-
];
|
|
83
|
-
})))).flat();
|
|
84
|
-
return [...result, { fileName: 'package.json', content: packageJson }];
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
export default generateWrapperCode;
|
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
import { getResourceExportDir } from '@blocklet/sdk/lib/component';
|
|
11
|
-
import { spawn } from 'child_process';
|
|
12
|
-
import { Router } from 'express';
|
|
13
|
-
import fs from 'fs';
|
|
14
|
-
import path, { join } from 'path';
|
|
15
|
-
import { findComponentFiles } from './utils';
|
|
16
|
-
const DID = 'z2qa7rr3eUyVnWp2PCxEVARuUfLFh6cE5V2xV';
|
|
17
|
-
const RESOURCE_TYPE = 'block';
|
|
18
|
-
const allTag = '@ALL_COMPONENTS';
|
|
19
|
-
export function copyFile(src, dest) {
|
|
20
|
-
return new Promise((resolve, reject) => {
|
|
21
|
-
const readStream = fs.createReadStream(src);
|
|
22
|
-
const writeStream = fs.createWriteStream(dest);
|
|
23
|
-
readStream.on('error', reject);
|
|
24
|
-
writeStream.on('error', reject);
|
|
25
|
-
writeStream.on('finish', resolve);
|
|
26
|
-
readStream.pipe(writeStream);
|
|
27
|
-
});
|
|
28
|
-
}
|
|
29
|
-
export function copyDirectory(src, dest) {
|
|
30
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
31
|
-
yield fs.promises.mkdir(dest, { recursive: true });
|
|
32
|
-
const entries = yield fs.promises.readdir(src, { withFileTypes: true });
|
|
33
|
-
for (const entry of entries) {
|
|
34
|
-
const srcPath = path.join(src, entry.name);
|
|
35
|
-
const destPath = path.join(dest, entry.name);
|
|
36
|
-
if (entry.isDirectory()) {
|
|
37
|
-
yield copyDirectory(srcPath, destPath);
|
|
38
|
-
}
|
|
39
|
-
else {
|
|
40
|
-
yield copyFile(srcPath, destPath);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
}
|
|
45
|
-
export function copyRecursive(src, dest) {
|
|
46
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
47
|
-
const srcStats = yield fs.promises.stat(src);
|
|
48
|
-
if (srcStats.isDirectory()) {
|
|
49
|
-
yield copyDirectory(src, dest);
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
yield copyFile(src, dest);
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
const getExportDir = (projectId, releaseId) => {
|
|
57
|
-
const exportDir = getResourceExportDir({ projectId, releaseId });
|
|
58
|
-
const dir = join(exportDir, DID, RESOURCE_TYPE);
|
|
59
|
-
return dir;
|
|
60
|
-
};
|
|
61
|
-
export const initResourceRouter = Router();
|
|
62
|
-
initResourceRouter.get('/resources', (_req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
|
63
|
-
const resources = [];
|
|
64
|
-
const rootDir = process.cwd();
|
|
65
|
-
const files = findComponentFiles({ cwd: rootDir });
|
|
66
|
-
for (const file of files) {
|
|
67
|
-
// const filePath = path.join(rootDir, file);
|
|
68
|
-
// const fileContent = fs.readFileSync(filePath, 'utf8');
|
|
69
|
-
const { blockName } = file;
|
|
70
|
-
resources.push({
|
|
71
|
-
id: blockName,
|
|
72
|
-
name: blockName,
|
|
73
|
-
description: '',
|
|
74
|
-
images: [],
|
|
75
|
-
url: '',
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
res.json({
|
|
79
|
-
resources: [
|
|
80
|
-
{
|
|
81
|
-
id: allTag,
|
|
82
|
-
name: 'All Blocks',
|
|
83
|
-
description: 'Select All Blocks',
|
|
84
|
-
images: [],
|
|
85
|
-
url: '',
|
|
86
|
-
children: resources,
|
|
87
|
-
},
|
|
88
|
-
],
|
|
89
|
-
});
|
|
90
|
-
}));
|
|
91
|
-
initResourceRouter.post('/resources', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
|
|
92
|
-
const { resources, projectId, releaseId } = req.body;
|
|
93
|
-
// ignore all tag
|
|
94
|
-
const componentIds = resources.filter((resource) => resource.id !== allTag);
|
|
95
|
-
try {
|
|
96
|
-
// Execute build command with filtered components
|
|
97
|
-
const buildProcess = spawn('pnpm', ['run', 'build-lib'], {
|
|
98
|
-
stdio: 'inherit',
|
|
99
|
-
shell: true,
|
|
100
|
-
env: Object.assign(Object.assign({}, process.env), { FORCE_COLOR: '1', BLOCK_FILTER: componentIds.join(',') }),
|
|
101
|
-
});
|
|
102
|
-
yield new Promise((resolve, reject) => {
|
|
103
|
-
buildProcess.on('close', (code) => {
|
|
104
|
-
if (code === 0)
|
|
105
|
-
resolve(null);
|
|
106
|
-
else
|
|
107
|
-
reject(new Error(`Build process exited with code ${code}`));
|
|
108
|
-
});
|
|
109
|
-
});
|
|
110
|
-
const dir = getExportDir(projectId, releaseId);
|
|
111
|
-
fs.rmSync(dir, { recursive: true, force: true });
|
|
112
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
113
|
-
const rootDir = process.cwd();
|
|
114
|
-
const tmpPackage = join(rootDir, 'lib');
|
|
115
|
-
yield copyRecursive(tmpPackage, dir);
|
|
116
|
-
fs.rmSync(tmpPackage, { recursive: true, force: true });
|
|
117
|
-
res.json({ success: true });
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
console.error('Build failed:', error);
|
|
121
|
-
res.status(500).json({ error: 'Build failed' });
|
|
122
|
-
}
|
|
123
|
-
}));
|
|
124
|
-
export default initResourceRouter;
|
|
@@ -1,140 +0,0 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
// eslint-disable-next-line import/no-unresolved
|
|
11
|
-
// import typescript from '@rollup/plugin-typescript';
|
|
12
|
-
import { readFileSync, existsSync } from 'fs';
|
|
13
|
-
import * as path from 'path';
|
|
14
|
-
import pages, { DefaultPageStrategy } from 'vite-plugin-react-pages';
|
|
15
|
-
import { findComponentFiles, setBlockEntryFilesPattern, getBlockEntryFilesPattern, getBlockName, logger, } from '../utils';
|
|
16
|
-
import { initHtmlPreviewTransformPlugin, VIRTUAL_MODULE_ID } from './vite-plugin-html-transform';
|
|
17
|
-
// import initRemoteScriptLocalizerPlugin from './vite-plugin-remote-script-localizer';
|
|
18
|
-
export function initBlockStudioPlugins(options) {
|
|
19
|
-
const workingDir = (options === null || options === void 0 ? void 0 : options.cwd) || process.cwd();
|
|
20
|
-
const entryFilesPattern = (options === null || options === void 0 ? void 0 : options.entryFilesPattern) || getBlockEntryFilesPattern();
|
|
21
|
-
setBlockEntryFilesPattern(entryFilesPattern);
|
|
22
|
-
// fallback to __dirname if _theme.tsx not exists
|
|
23
|
-
const pagesDir = existsSync(path.join(workingDir, '_theme.tsx')) ? workingDir : __dirname.replace('cjs', 'esm');
|
|
24
|
-
logger.log('initBlockStudioPlugins options', {
|
|
25
|
-
cwd: workingDir,
|
|
26
|
-
entryFilesPattern: getBlockEntryFilesPattern(),
|
|
27
|
-
pagesDir,
|
|
28
|
-
});
|
|
29
|
-
return [
|
|
30
|
-
// {
|
|
31
|
-
// name: 'vite-plugin-block-studio-dev',
|
|
32
|
-
// enforce: 'pre',
|
|
33
|
-
// transformIndexHtml(html) {
|
|
34
|
-
// // Ensure required content exists in index.html
|
|
35
|
-
// if (!html.includes('<div id="root"></div>')) {
|
|
36
|
-
// html = html.replace(/<body[^>]*>/, '$&<div id="root"></div>');
|
|
37
|
-
// }
|
|
38
|
-
// if (!html.includes('/@pages-infra/main.js')) {
|
|
39
|
-
// html = html.replace('</body>', '<script type="module" src="/@pages-infra/main.js"></script></body>');
|
|
40
|
-
// }
|
|
41
|
-
// return html;
|
|
42
|
-
// },
|
|
43
|
-
// },
|
|
44
|
-
{
|
|
45
|
-
name: 'vite-plugin-block-studio-build',
|
|
46
|
-
enforce: 'pre',
|
|
47
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
48
|
-
config(_config) {
|
|
49
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
50
|
-
var _a;
|
|
51
|
-
const filterModules = process.argv.includes('--filter')
|
|
52
|
-
? (_a = process.argv[process.argv.indexOf('--filter') + 1]) === null || _a === void 0 ? void 0 : _a.split(',')
|
|
53
|
-
: null;
|
|
54
|
-
const multiMode = !!process.argv.includes('--multi');
|
|
55
|
-
const name = yield import(`${workingDir}/package.json`).then((res) => res.name).catch(() => 'MyLib');
|
|
56
|
-
return {
|
|
57
|
-
build: {
|
|
58
|
-
cssCodeSplit: false,
|
|
59
|
-
lib: {
|
|
60
|
-
name,
|
|
61
|
-
entry: Object.assign({}, Object.fromEntries(findComponentFiles({ cwd: workingDir })
|
|
62
|
-
.map((entry) => {
|
|
63
|
-
const { blockName } = entry;
|
|
64
|
-
const { isHtml } = entry;
|
|
65
|
-
const { file } = entry;
|
|
66
|
-
if (isHtml) {
|
|
67
|
-
return [blockName, `${VIRTUAL_MODULE_ID}?dir=${path.dirname(file)}`];
|
|
68
|
-
}
|
|
69
|
-
return [blockName, path.resolve(workingDir, file)];
|
|
70
|
-
})
|
|
71
|
-
.filter(Boolean)
|
|
72
|
-
.filter(([blockName]) => !filterModules || filterModules.includes(blockName || '')))),
|
|
73
|
-
// multiMode not support umd
|
|
74
|
-
formats: ['es', multiMode ? 'umd' : 'cjs'],
|
|
75
|
-
fileName: (format, entryName) => `${format}/${entryName}.js`,
|
|
76
|
-
},
|
|
77
|
-
rollupOptions: {
|
|
78
|
-
// make sure to externalize deps that shouldn't be bundled
|
|
79
|
-
// into your library
|
|
80
|
-
external: ['react', 'crypto'],
|
|
81
|
-
output: {
|
|
82
|
-
// Provide global variables to use in the UMD build
|
|
83
|
-
globals: {
|
|
84
|
-
react: 'React',
|
|
85
|
-
},
|
|
86
|
-
paths: {
|
|
87
|
-
// Redirect 'react' imports to '@blocklet/pages-kit/builtin/react'
|
|
88
|
-
// react: '@blocklet/pages-kit/builtin/react',
|
|
89
|
-
},
|
|
90
|
-
},
|
|
91
|
-
},
|
|
92
|
-
},
|
|
93
|
-
};
|
|
94
|
-
});
|
|
95
|
-
},
|
|
96
|
-
},
|
|
97
|
-
// @ts-ignore
|
|
98
|
-
pages({
|
|
99
|
-
pagesDir,
|
|
100
|
-
pageStrategy: new DefaultPageStrategy({
|
|
101
|
-
extraFindPages: (_pagesDir, helpers) => __awaiter(this, void 0, void 0, function* () {
|
|
102
|
-
helpers.watchFiles(workingDir, getBlockEntryFilesPattern(), function fileHandler(file, api) {
|
|
103
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
104
|
-
const { relative, path: filePath } = file;
|
|
105
|
-
const isHtml = relative.endsWith('.html');
|
|
106
|
-
const blockName = getBlockName(relative);
|
|
107
|
-
const pageId = `/${blockName}`;
|
|
108
|
-
api.addPageData({
|
|
109
|
-
pageId,
|
|
110
|
-
dataPath: isHtml ? `${VIRTUAL_MODULE_ID}?dir=${path.dirname(filePath)}` : filePath,
|
|
111
|
-
staticData: isHtml
|
|
112
|
-
? {
|
|
113
|
-
isHtmlPreview: true,
|
|
114
|
-
dataPath: filePath,
|
|
115
|
-
blockName,
|
|
116
|
-
}
|
|
117
|
-
: Object.assign(Object.assign({}, (yield helpers.extractStaticData(file))), { code: readFileSync(file.path, 'utf-8'), dataPath: filePath, blockName }),
|
|
118
|
-
});
|
|
119
|
-
});
|
|
120
|
-
});
|
|
121
|
-
}),
|
|
122
|
-
}),
|
|
123
|
-
}),
|
|
124
|
-
// https://github.com/rollup/plugins/tree/master/packages/typescript#noforceemit
|
|
125
|
-
// typescript({
|
|
126
|
-
// declaration: true,
|
|
127
|
-
// emitDeclarationOnly: true,
|
|
128
|
-
// noForceEmit: true,
|
|
129
|
-
// declarationDir: path.resolve(workingDir, 'lib/types'),
|
|
130
|
-
// rootDir: path.resolve(workingDir),
|
|
131
|
-
// }),
|
|
132
|
-
initHtmlPreviewTransformPlugin(),
|
|
133
|
-
// initRemoteScriptLocalizerPlugin({
|
|
134
|
-
// tempDir: 'temp/remote-scripts', // 可选,默认值
|
|
135
|
-
// maxConcurrent: 5, // 可选,默认值
|
|
136
|
-
// timeout: 30 * 1000, // 可选,默认值 30 秒
|
|
137
|
-
// }),
|
|
138
|
-
];
|
|
139
|
-
}
|
|
140
|
-
export default initBlockStudioPlugins;
|
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
import { existsSync, readFileSync } from 'fs';
|
|
11
|
-
import { basename, dirname, join } from 'path';
|
|
12
|
-
export const VIRTUAL_MODULE_ID = 'virtual:html-preview';
|
|
13
|
-
export const RESOLVED_VIRTUAL_MODULE_ID = `\0${VIRTUAL_MODULE_ID}`;
|
|
14
|
-
// Helper function to check if a path is relative
|
|
15
|
-
const isRelativePath = (path) => {
|
|
16
|
-
return path.startsWith('./') || path.startsWith('../') || (!path.startsWith('http') && !path.startsWith('//'));
|
|
17
|
-
};
|
|
18
|
-
function extractExternalResources(html, _dirPath) {
|
|
19
|
-
const external = {
|
|
20
|
-
js: [],
|
|
21
|
-
css: [],
|
|
22
|
-
};
|
|
23
|
-
// 提取 script src
|
|
24
|
-
const scriptMatches = html.matchAll(/<script.*?src=["'](.*?)["']/g);
|
|
25
|
-
for (const match of scriptMatches) {
|
|
26
|
-
const src = match[1] || '';
|
|
27
|
-
if (!isRelativePath(src)) {
|
|
28
|
-
external.js.push(src);
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
// 提取 link href
|
|
32
|
-
const linkMatches = html.matchAll(/<link.*?href=["'](.*?)["'].*?>/g);
|
|
33
|
-
for (const match of linkMatches) {
|
|
34
|
-
if (match[0].includes('stylesheet')) {
|
|
35
|
-
const href = match[1] || '';
|
|
36
|
-
if (!isRelativePath(href)) {
|
|
37
|
-
external.css.push(href);
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
// 只移除相对路径引用,保留 HTML 结构
|
|
42
|
-
const htmlWithoutRelativeImport = html
|
|
43
|
-
.replace(/<script.*?src=["']((?:\.|\.\.)\/.+?)["'].*?><\/script>/g, '') // 移除相对路径的 script 标签
|
|
44
|
-
.replace(/<link.*?href=["']((?:\.|\.\.)\/.+?)["'].*?>/g, '') // 移除相对路径的 link 标签
|
|
45
|
-
.trim();
|
|
46
|
-
return { external, htmlWithoutRelativeImport };
|
|
47
|
-
}
|
|
48
|
-
function readHtmlFiles(dirPath) {
|
|
49
|
-
const htmlPath = join(dirPath, 'index.html');
|
|
50
|
-
if (!existsSync(htmlPath)) {
|
|
51
|
-
throw new Error(`No index.html found in ${dirPath}`);
|
|
52
|
-
}
|
|
53
|
-
const html = readFileSync(htmlPath, 'utf-8');
|
|
54
|
-
const cssFiles = [];
|
|
55
|
-
const jsFiles = [];
|
|
56
|
-
const cssContents = [];
|
|
57
|
-
const jsContents = [];
|
|
58
|
-
// Process imports in JS/CSS files
|
|
59
|
-
function processFile(filePath, type, processedFiles = new Set()) {
|
|
60
|
-
if (processedFiles.has(filePath))
|
|
61
|
-
return '';
|
|
62
|
-
processedFiles.add(filePath);
|
|
63
|
-
let content = readFileSync(filePath, 'utf-8');
|
|
64
|
-
if (type === 'js') {
|
|
65
|
-
const importMatches = content.matchAll(/import\s+['"](.+?)['"]/g);
|
|
66
|
-
for (const match of importMatches) {
|
|
67
|
-
const importPath = match[1] || '';
|
|
68
|
-
if (isRelativePath(importPath)) {
|
|
69
|
-
const importFilePath = join(dirname(filePath), importPath);
|
|
70
|
-
const resolvedPath = importFilePath.endsWith('.js') ? importFilePath : `${importFilePath}.js`;
|
|
71
|
-
if (existsSync(resolvedPath)) {
|
|
72
|
-
const importedContent = processFile(resolvedPath, 'js', processedFiles);
|
|
73
|
-
content = content.replace(match[0], '');
|
|
74
|
-
content = `/* START: imported from ${importPath} */
|
|
75
|
-
${importedContent.trim()}
|
|
76
|
-
/* END: imported from ${importPath} */
|
|
77
|
-
${content.trim()}`;
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
// 标记不存在的导入
|
|
81
|
-
content = content.replace(match[0], `/* SKIP: file not found - ${importPath} */`);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
const importMatches = content.matchAll(/@import\s+['"](.+?)['"];?/g);
|
|
88
|
-
for (const match of importMatches) {
|
|
89
|
-
const importPath = match[1] || '';
|
|
90
|
-
if (isRelativePath(importPath)) {
|
|
91
|
-
const importFilePath = join(dirname(filePath), importPath);
|
|
92
|
-
const resolvedPath = importFilePath.endsWith('.css') ? importFilePath : `${importFilePath}.css`;
|
|
93
|
-
if (existsSync(resolvedPath)) {
|
|
94
|
-
const importedContent = processFile(resolvedPath, 'css', processedFiles);
|
|
95
|
-
content = content.replace(match[0], '');
|
|
96
|
-
content = `/* START: imported from ${importPath} */
|
|
97
|
-
${importedContent.trim()}
|
|
98
|
-
/* END: imported from ${importPath} */
|
|
99
|
-
${content.trim()}`;
|
|
100
|
-
}
|
|
101
|
-
else {
|
|
102
|
-
// 标记不存在的导入
|
|
103
|
-
content = content.replace(match[0], `/* SKIP: file not found - ${importPath} */`);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
return content;
|
|
109
|
-
}
|
|
110
|
-
// Extract relative paths from HTML
|
|
111
|
-
const scriptMatches = html.matchAll(/<script.*?src=["'](.*?)["']/g);
|
|
112
|
-
const linkMatches = html.matchAll(/<link.*?href=["'](.*?)["'].*?>/g);
|
|
113
|
-
// Process JS files
|
|
114
|
-
for (const match of scriptMatches) {
|
|
115
|
-
const src = match[1] || '';
|
|
116
|
-
if (isRelativePath(src)) {
|
|
117
|
-
const filePath = join(dirPath, src);
|
|
118
|
-
if (existsSync(filePath)) {
|
|
119
|
-
jsFiles.push(src);
|
|
120
|
-
jsContents.push(processFile(filePath, 'js', new Set()));
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
// Process CSS files
|
|
125
|
-
for (const match of linkMatches) {
|
|
126
|
-
if (match[0].includes('stylesheet')) {
|
|
127
|
-
const href = match[1] || '';
|
|
128
|
-
if (isRelativePath(href)) {
|
|
129
|
-
const filePath = join(dirPath, href);
|
|
130
|
-
if (existsSync(filePath)) {
|
|
131
|
-
cssFiles.push(href);
|
|
132
|
-
cssContents.push(processFile(filePath, 'css', new Set()));
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
const { external, htmlWithoutRelativeImport } = extractExternalResources(html, dirPath);
|
|
138
|
-
const commonCdnDomains = [
|
|
139
|
-
'https://*.jsdelivr.net',
|
|
140
|
-
'https://*.unpkg.com',
|
|
141
|
-
'https://*.cloudflare.com',
|
|
142
|
-
'https://*.bootstrapcdn.com',
|
|
143
|
-
'https://*.googleapis.com',
|
|
144
|
-
'https://cdn.skypack.dev',
|
|
145
|
-
'https://*.cdnjs.com',
|
|
146
|
-
];
|
|
147
|
-
const cspDirectives = [
|
|
148
|
-
"default-src 'none'",
|
|
149
|
-
`script-src 'unsafe-inline' 'unsafe-eval' ${commonCdnDomains.join(' ')} ${external.js.join(' ')}`,
|
|
150
|
-
`style-src 'unsafe-inline' ${commonCdnDomains.join(' ')} ${external.css.join(' ')}`,
|
|
151
|
-
"img-src 'self' data: https:",
|
|
152
|
-
`connect-src 'self' ${commonCdnDomains.join(' ')} https:`,
|
|
153
|
-
"frame-src 'none'",
|
|
154
|
-
"object-src 'none'",
|
|
155
|
-
"base-uri 'none'",
|
|
156
|
-
"form-action 'none'",
|
|
157
|
-
"font-src 'none'",
|
|
158
|
-
"media-src 'self' https:",
|
|
159
|
-
"manifest-src 'none'",
|
|
160
|
-
"worker-src 'none'",
|
|
161
|
-
].join('; ');
|
|
162
|
-
const securityHeaders = `
|
|
163
|
-
<meta http-equiv="Content-Security-Policy" content="${cspDirectives}">
|
|
164
|
-
<meta http-equiv="X-Content-Type-Options" content="nosniff">
|
|
165
|
-
<meta http-equiv="Referrer-Policy" content="no-referrer">
|
|
166
|
-
<meta http-equiv="Permissions-Policy" content="accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()">`;
|
|
167
|
-
// 将处理后的相对路径引入的 CSS 和 JS 注入到 HTML 中
|
|
168
|
-
const htmlContent = htmlWithoutRelativeImport
|
|
169
|
-
.replace('<head>', `<head>${securityHeaders}`)
|
|
170
|
-
.replace('</head>', `${cssContents.map((css) => `<style>${css.trim()}</style>`).join('\n')}
|
|
171
|
-
</head>`)
|
|
172
|
-
.replace('</body>', `
|
|
173
|
-
${jsContents.map((js) => `<script>${js}</script>`).join('\n')}
|
|
174
|
-
</body>
|
|
175
|
-
`)
|
|
176
|
-
.trim();
|
|
177
|
-
return {
|
|
178
|
-
html: JSON.stringify(htmlContent).replace(/`/g, '\\`'),
|
|
179
|
-
css: cssContents,
|
|
180
|
-
js: jsContents,
|
|
181
|
-
cssFiles,
|
|
182
|
-
jsFiles,
|
|
183
|
-
external,
|
|
184
|
-
name: basename(dirPath),
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
function generateComponent(content, _isDev = true) {
|
|
188
|
-
const htmlContent = content.html;
|
|
189
|
-
const { name } = content;
|
|
190
|
-
return `import { createElement } from 'react';
|
|
191
|
-
|
|
192
|
-
export default function HtmlPreview() {
|
|
193
|
-
return createElement('iframe', {
|
|
194
|
-
style: { border: 'none', width: '100%', height: '100%' },
|
|
195
|
-
sandbox: 'allow-scripts',
|
|
196
|
-
title: 'Preview ${name}',
|
|
197
|
-
srcDoc: ${htmlContent}
|
|
198
|
-
});
|
|
199
|
-
}`;
|
|
200
|
-
}
|
|
201
|
-
export function initHtmlPreviewTransformPlugin() {
|
|
202
|
-
const htmlCache = new Map();
|
|
203
|
-
let isBuild = false;
|
|
204
|
-
return {
|
|
205
|
-
name: 'vite-plugin-html-preview',
|
|
206
|
-
configResolved(config) {
|
|
207
|
-
isBuild = config.command === 'build';
|
|
208
|
-
},
|
|
209
|
-
resolveId(id) {
|
|
210
|
-
// 识别 virtual:html-preview 的 id,build 的时候会返回一个带文件路径的 id,所以这里需要使用 includes 而不是 startsWith
|
|
211
|
-
if (id.includes(VIRTUAL_MODULE_ID)) {
|
|
212
|
-
const dirPath = id.split('?dir=')[1];
|
|
213
|
-
return `${RESOLVED_VIRTUAL_MODULE_ID}?dir=${dirPath}`;
|
|
214
|
-
}
|
|
215
|
-
return null;
|
|
216
|
-
},
|
|
217
|
-
load(id) {
|
|
218
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
219
|
-
const useCache = false;
|
|
220
|
-
if (id.startsWith(RESOLVED_VIRTUAL_MODULE_ID)) {
|
|
221
|
-
const dirPath = id.split('?dir=')[1] || '';
|
|
222
|
-
// 使用缓存避免重复读取
|
|
223
|
-
let content = useCache ? htmlCache.get(dirPath) : null;
|
|
224
|
-
if (!content) {
|
|
225
|
-
content = readHtmlFiles(dirPath);
|
|
226
|
-
if (useCache) {
|
|
227
|
-
htmlCache.set(dirPath, content);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
return generateComponent(content, !isBuild);
|
|
231
|
-
}
|
|
232
|
-
return null;
|
|
233
|
-
});
|
|
234
|
-
},
|
|
235
|
-
// 清理缓存
|
|
236
|
-
buildEnd() {
|
|
237
|
-
htmlCache.clear();
|
|
238
|
-
},
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
export default initHtmlPreviewTransformPlugin;
|