@cfp-studio/core 1.0.0 → 1.0.2

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/dist/index.mjs CHANGED
@@ -1,337 +1,9 @@
1
- import { decodePreviewableId } from '@cfp-studio/analyzer-api';
2
- import { RPCs } from '@cfp-studio/api';
3
- import { UNKNOWN_TYPE } from '@cfp-studio/type-analyzer';
4
- import { createStackedReader, createFileSystemReader } from '@cfp-studio/vfs';
5
- import express from 'express';
6
- import cors from 'cors';
7
- import fs$1 from 'fs-extra';
8
- import { createHttpTerminator } from 'http-terminator';
9
- import { createRequire } from 'node:module';
10
- import path from 'node:path';
11
- import pino from 'pino';
12
- import PinoPretty from 'pino-pretty';
13
- import { exclusivePromiseRunner } from 'exclusive-promises';
14
- import fs from 'node:fs';
15
- import url from 'node:url';
16
- import { globby } from 'globby';
17
- import net from 'node:net';
18
- import { assertNever } from 'assert-never';
19
- import axios from 'axios';
20
- import viteTsconfigPaths from '@fwouts/vite-tsconfig-paths';
21
- import { PREVIEW_CONFIG_NAMES, readConfig } from '@cfp-studio/config';
22
- import fakeExportedTypesPlugin from 'rollup-plugin-friendly-type-imports';
23
- import { loadTsconfig } from 'tsconfig-paths/lib/tsconfig-loader.js';
24
- import * as vite from 'vite';
25
- import { transformWithEsbuild, searchForWorkspaceRoot } from 'vite';
26
- import { z } from 'zod';
27
- import { escape } from 'html-escaper';
28
- import { launchEditorMiddleware } from '@cfp-studio/middleware';
29
-
30
- function getCacheDir(rootDir) {
31
- try {
32
- const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
33
- const { version } = JSON.parse(
34
- // 同步读取 package.json 文件,使用 UTF-8 编码
35
- fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8")
36
- );
37
- return path.resolve(rootDir, "node_modules", ".previewjs", `v${version}`);
38
- } catch (e) {
39
- throw new Error(`\u65E0\u6CD5\u83B7\u53D6 @cfp-studio/core \u7684\u7248\u672C\u53F7.
40
- ${e}`);
41
- }
42
- }
43
-
44
- async function findFiles(rootDir, pattern, options = {}) {
45
- const gitRootPath = await findGitRoot(rootDir);
46
- const relativePath = path.relative(gitRootPath, rootDir);
47
- const relativePrefix = relativePath ? relativePath + path.sep : "";
48
- const files = await globby(relativePrefix + pattern, {
49
- gitignore: true,
50
- ignore: ["**/node_modules/**"],
51
- cwd: gitRootPath,
52
- absolute: true,
53
- followSymbolicLinks: false,
54
- suppressErrors: true,
55
- deep: options.maxDepth
56
- });
57
- let normalizedRootDirPath = rootDir.replace(/\\/g, "/");
58
- if (!normalizedRootDirPath.endsWith("/")) {
59
- normalizedRootDirPath += "/";
60
- }
61
- return files.filter((f) => f.startsWith(normalizedRootDirPath)).sort();
62
- }
63
- async function findGitRoot(dirPath, fallback = dirPath) {
64
- try {
65
- if (await fs$1.exists(path.join(dirPath, ".git"))) {
66
- return dirPath;
67
- }
68
- const parentDirPath = path.dirname(dirPath);
69
- if (!parentDirPath || parentDirPath === dirPath) {
70
- return fallback;
71
- }
72
- return findGitRoot(parentDirPath, fallback);
73
- } catch {
74
- return fallback;
75
- }
76
- }
77
-
78
- const FILES_REQUIRING_REDETECTION = /* @__PURE__ */ new Set([
79
- "jsconfig.json",
80
- "tsconfig.json",
81
- "package.json",
82
- "package-lock.json",
83
- "pnpm-lock.yaml",
84
- "yarn.lock"
85
- ]);
86
- const oneAtATime = exclusivePromiseRunner();
87
- function crawlFiles(logger, workspace, frameworkPlugin, options = {}) {
88
- return oneAtATime(async () => {
89
- logger.debug(
90
- `\u5F00\u59CB\u626B\u63CF\u7EC4\u4EF6\uFF0C\u626B\u63CF\u53C2\u6570: ${JSON.stringify(options)}`
91
- );
92
- const detectionStartTimestamp = Date.now();
93
- const cacheFilePath = path.join(
94
- getCacheDir(workspace.rootDir),
95
- "components.json"
96
- );
97
- const absoluteFilePaths = await (async () => {
98
- if (options.filePaths) {
99
- return options.filePaths.map(
100
- (filePath) => path.join(workspace.rootDir, filePath)
101
- );
102
- }
103
- logger.debug(`\u626B\u63CF\u76EE\u5F55: ${workspace.rootDir}\uFF0C\u91C7\u96C6\u53EF\u626B\u63CF\u6587\u4EF6`);
104
- const filePaths = await findFiles(
105
- workspace.rootDir,
106
- "**/*.@(js|jsx|ts|tsx|svelte|vue)"
107
- );
108
- logger.debug(`\u627E\u5230 ${filePaths.length} \u4E2A\u5305\u542B\u7EC4\u4EF6\u7684\u6587\u4EF6`);
109
- return filePaths;
110
- })();
111
- const filePathsSet = new Set(
112
- absoluteFilePaths.map(
113
- (absoluteFilePath) => path.relative(workspace.rootDir, absoluteFilePath).replace(/\\/g, "/")
114
- )
115
- );
116
- let existingCache = {
117
- detectionStartTimestamp: 0,
118
- components: [],
119
- stories: []
120
- };
121
- if (fs$1.existsSync(cacheFilePath)) {
122
- try {
123
- existingCache = JSON.parse(
124
- fs$1.readFileSync(cacheFilePath, "utf8")
125
- );
126
- } catch {
127
- logger.warn(`\u65E0\u6CD5\u8F6C\u6362 ${cacheFilePath} \u4E2D\u5B58\u50A8\u7684\u7F13\u5B58\u4FE1\u606F`);
128
- }
129
- }
130
- if (existingCache.detectionStartTimestamp < await detectionMinimalTimestamp(workspace.rootDir)) {
131
- existingCache = {
132
- detectionStartTimestamp: 0,
133
- components: [],
134
- stories: []
135
- };
136
- }
137
- const changedAbsoluteFilePaths = absoluteFilePaths.filter(
138
- (absoluteFilePath) => {
139
- const entry = workspace.reader.readSync(absoluteFilePath);
140
- return entry?.kind === "file" && (options.forceRefresh || entry.lastModifiedMillis() >= existingCache.detectionStartTimestamp);
141
- }
142
- );
143
- const refreshedFilePaths = new Set(
144
- changedAbsoluteFilePaths.map(
145
- (absoluteFilePath) => path.relative(workspace.rootDir, absoluteFilePath).replace(/\\/g, "/")
146
- )
147
- );
148
- const shouldRecycle = ({ id }) => {
149
- const filePath = decodePreviewableId(id).filePath;
150
- return filePathsSet.has(filePath) && !refreshedFilePaths.has(filePath);
151
- };
152
- const recycledComponents = existingCache.components.filter(shouldRecycle);
153
- const recycledStories = existingCache.stories.filter(shouldRecycle);
154
- const { components: refreshedComponents, stories: refreshedStories } = await analyzeCore(
155
- logger,
156
- workspace,
157
- frameworkPlugin,
158
- changedAbsoluteFilePaths
159
- );
160
- const components = [...recycledComponents, ...refreshedComponents];
161
- const stories = [...recycledStories, ...refreshedStories];
162
- if (!options.filePaths) {
163
- await fs$1.mkdirp(path.dirname(cacheFilePath));
164
- const updatedCache = {
165
- detectionStartTimestamp,
166
- components,
167
- stories
168
- };
169
- await fs$1.writeFile(cacheFilePath, JSON.stringify(updatedCache));
170
- }
171
- return { components, stories };
172
- });
173
- }
174
- async function analyzeCore(logger, workspace, frameworkPlugin, changedAbsoluteFilePaths) {
175
- const components = [];
176
- const stories = [];
177
- if (changedAbsoluteFilePaths.length === 0) {
178
- return { components, stories };
179
- }
180
- logger.debug(
181
- `\u5728\u4E0B\u8FF0\u6587\u4EF6\u4E2D\u67E5\u627E\u7EC4\u4EF6:
182
- - ${changedAbsoluteFilePaths.map(
183
- (absoluteFilePath) => path.relative(workspace.rootDir, absoluteFilePath)
184
- ).join("\n- ")}`
185
- );
186
- const found = await frameworkPlugin.crawlFiles(changedAbsoluteFilePaths);
187
- logger.debug("\u7EC4\u4EF6\u68C0\u6D4B\u5B8C\u6210");
188
- for (const component of found.components) {
189
- components.push({
190
- id: component.id,
191
- sourcePosition: component.sourcePosition,
192
- exported: component.exported
193
- });
194
- }
195
- for (const story of found.stories) {
196
- stories.push({
197
- id: story.id,
198
- sourcePosition: story.sourcePosition,
199
- associatedComponentId: story.associatedComponent?.id || null
200
- });
201
- }
202
- return { components, stories };
203
- }
204
- async function detectionMinimalTimestamp(rootDir) {
205
- const nodeModulesPath = path.join(rootDir, "node_modules");
206
- let lastModifiedMillis = 0;
207
- if (await fs$1.pathExists(nodeModulesPath)) {
208
- for (const subdirectory of await fs$1.readdir(nodeModulesPath)) {
209
- const subdirectoryPath = path.join(nodeModulesPath, subdirectory);
210
- const stat = await fs$1.lstat(subdirectoryPath);
211
- if (stat.isDirectory() || stat.isSymbolicLink()) {
212
- lastModifiedMillis = Math.max(lastModifiedMillis, stat.mtimeMs);
213
- }
214
- }
215
- }
216
- for (const f of FILES_REQUIRING_REDETECTION) {
217
- const filePath = path.join(rootDir, f);
218
- if (await fs$1.pathExists(filePath)) {
219
- const stat = await fs$1.stat(filePath);
220
- lastModifiedMillis = Math.max(lastModifiedMillis, stat.mtimeMs);
221
- }
222
- }
223
- return lastModifiedMillis;
224
- }
225
-
226
- async function getFreePort(min) {
227
- for (let port = min; ; port++) {
228
- if (await isAvailable(port)) {
229
- return port;
230
- }
231
- }
232
- }
233
- async function isAvailable(port) {
234
- return new Promise((resolve) => {
235
- const server = net.createServer();
236
- server.unref();
237
- server.on("error", () => resolve(false));
238
- server.listen(port, () => {
239
- server.close(() => {
240
- resolve(true);
241
- });
242
- });
243
- });
244
- }
245
-
246
- const require$1 = createRequire(import.meta.url);
247
- async function extractPackageDependencies(logger, rootDir) {
248
- const packageJsonPath = path.join(rootDir, "package.json");
249
- if (!await fs$1.pathExists(packageJsonPath)) {
250
- return {};
251
- }
252
- const { dependencies, devDependencies, peerDependencies } = JSON.parse(
253
- await fs$1.readFile(packageJsonPath, "utf8")
254
- );
255
- const allDependencies = {
256
- ...dependencies,
257
- ...devDependencies,
258
- ...peerDependencies
259
- };
260
- const dependenciesMap = /* @__PURE__ */ new Map();
261
- for (const [name, version] of Object.entries(allDependencies)) {
262
- let majorVersion = 0;
263
- if (typeof version === "string") {
264
- if (version.startsWith("^") || version.startsWith("~")) {
265
- majorVersion = Number.parseInt(version.slice(1));
266
- } else {
267
- majorVersion = Number.parseInt(version);
268
- }
269
- }
270
- const readInstalledVersion = async () => {
271
- try {
272
- const moduleEntryPath = findModuleEntryPath(name, rootDir);
273
- let packagePath = moduleEntryPath;
274
- while (packagePath !== path.dirname(packagePath)) {
275
- const candidatePackageJsonPath = path.join(
276
- packagePath,
277
- "package.json"
278
- );
279
- if (fs$1.existsSync(candidatePackageJsonPath)) {
280
- const packageInfo = JSON.parse(
281
- await fs$1.readFile(candidatePackageJsonPath, "utf8")
282
- );
283
- if (typeof packageInfo.version === "string") {
284
- return packageInfo.version;
285
- }
286
- throw new Error(`\u5305: ${candidatePackageJsonPath} \u7684\u7248\u672C\u53F7\u5F02\u5E38`);
287
- }
288
- packagePath = path.dirname(packagePath);
289
- }
290
- throw new Error(
291
- `\u6839\u636E\u6A21\u5757: ${moduleEntryPath} \u7684\u5165\u53E3\u8DEF\u5F84\u65E0\u6CD5\u627E\u5230 package.json`
292
- );
293
- } catch (e) {
294
- logger.error(
295
- `\u65E0\u6CD5\u8BFB\u53D6\u5305: ${name} \u7684\u5B89\u88C5\u7248\u672C, \u4F60\u53EF\u80FD\u6CA1\u6709\u6B63\u786E\u5B89\u88C5\u9879\u76EE\u7684\u4F9D\u8D56\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u3002`,
296
- e
297
- );
298
- return null;
299
- }
300
- };
301
- dependenciesMap.set(name, { majorVersion, readInstalledVersion });
302
- }
303
- return Object.fromEntries(dependenciesMap);
304
- }
305
- function findModuleEntryPath(name, rootDir) {
306
- try {
307
- return require$1.resolve(name, {
308
- paths: [rootDir]
309
- });
310
- } catch (e) {
311
- if (e instanceof Error) {
312
- if ("code" in e && e.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") {
313
- const potentialMatch = e.message.match(
314
- /No "exports" main defined in (.*)(\/|\\)package\.json/
315
- );
316
- if (potentialMatch) {
317
- return potentialMatch[1] ?? "";
318
- }
319
- }
320
- }
321
- throw e;
322
- }
323
- }
324
-
325
- function generateHtmlError(message) {
326
- let _msg = message;
327
- if (_msg.startsWith("Error: Build failed with 1 error:\n")) {
328
- _msg = _msg.substring(message.indexOf("\n") + 1);
329
- }
330
- if (_msg.startsWith("Error:")) {
331
- _msg = _msg.substring(_msg.indexOf(":") + 1);
332
- }
333
- _msg = _msg.trim();
334
- return `<html>
1
+ import{decodePreviewableId as O}from"@cfp-studio/analyzer-api";import{RPCs as G}from"@cfp-studio/api";import{UNKNOWN_TYPE as fe}from"@cfp-studio/type-analyzer";import{createStackedReader as he,createFileSystemReader as z}from"@cfp-studio/vfs";import R from"express";import me from"cors";import w from"fs-extra";import{createHttpTerminator as ge}from"http-terminator";import{createRequire as Z}from"node:module";import a from"node:path";import we from"pino";import ve from"pino-pretty";import{exclusivePromiseRunner as ee}from"exclusive-promises";import Ee from"node:fs";import Fe from"node:url";import{globby as ye}from"globby";import Ce from"node:net";import{assertNever as De}from"assert-never";import be from"axios";import Pe from"@fwouts/vite-tsconfig-paths";import{PREVIEW_CONFIG_NAMES as je,readConfig as $e}from"@cfp-studio/config";import ke from"rollup-plugin-friendly-type-imports";import{loadTsconfig as Se}from"tsconfig-paths/lib/tsconfig-loader.js";import*as q from"vite";import{transformWithEsbuild as Ae,searchForWorkspaceRoot as _e}from"vite";import{z as A}from"zod";import{escape as Be}from"html-escaper";import{launchEditorMiddleware as xe}from"@cfp-studio/middleware";function te(r){try{const e=Fe.fileURLToPath(new URL(".",import.meta.url)),{version:t}=JSON.parse(Ee.readFileSync(a.resolve(e,"..","package.json"),"utf8"));return a.resolve(r,"node_modules",".previewjs",`v${t}`)}catch(e){throw new Error(`\u65E0\u6CD5\u83B7\u53D6 @cfp-studio/core \u7684\u7248\u672C\u53F7.
2
+ ${e}`)}}async function re(r,e,t={}){const o=await ie(r),i=a.relative(o,r),s=i?i+a.sep:"",n=await ye(s+e,{gitignore:!0,ignore:["**/node_modules/**"],cwd:o,absolute:!0,followSymbolicLinks:!1,suppressErrors:!0,deep:t.maxDepth});let u=r.replace(/\\/g,"/");return u.endsWith("/")||(u+="/"),n.filter(l=>l.startsWith(u)).sort()}async function ie(r,e=r){try{if(await w.exists(a.join(r,".git")))return r;const t=a.dirname(r);return!t||t===r?e:ie(t,e)}catch{return e}}const se=new Set(["jsconfig.json","tsconfig.json","package.json","package-lock.json","pnpm-lock.yaml","yarn.lock"]),Me=ee();function Oe(r,e,t,o={}){return Me(async()=>{r.debug(`\u5F00\u59CB\u626B\u63CF\u7EC4\u4EF6\uFF0C\u626B\u63CF\u53C2\u6570: ${JSON.stringify(o)}`);const i=Date.now(),s=a.join(te(e.rootDir),"components.json"),n=await(async()=>{if(o.filePaths)return o.filePaths.map(h=>a.join(e.rootDir,h));r.debug(`\u626B\u63CF\u76EE\u5F55: ${e.rootDir}\uFF0C\u91C7\u96C6\u53EF\u626B\u63CF\u6587\u4EF6`);const c=await re(e.rootDir,"**/*.@(js|jsx|ts|tsx|svelte|vue)");return r.debug(`\u627E\u5230 ${c.length} \u4E2A\u5305\u542B\u7EC4\u4EF6\u7684\u6587\u4EF6`),c})(),u=new Set(n.map(c=>a.relative(e.rootDir,c).replace(/\\/g,"/")));let l={detectionStartTimestamp:0,components:[],stories:[]};if(w.existsSync(s))try{l=JSON.parse(w.readFileSync(s,"utf8"))}catch{r.warn(`\u65E0\u6CD5\u8F6C\u6362 ${s} \u4E2D\u5B58\u50A8\u7684\u7F13\u5B58\u4FE1\u606F`)}l.detectionStartTimestamp<await We(e.rootDir)&&(l={detectionStartTimestamp:0,components:[],stories:[]});const p=n.filter(c=>{const h=e.reader.readSync(c);return h?.kind==="file"&&(o.forceRefresh||h.lastModifiedMillis()>=l.detectionStartTimestamp)}),d=new Set(p.map(c=>a.relative(e.rootDir,c).replace(/\\/g,"/"))),f=({id:c})=>{const h=O(c).filePath;return u.has(h)&&!d.has(h)},g=l.components.filter(f),m=l.stories.filter(f),{components:y,stories:D}=await Re(r,e,t,p),v=[...g,...y],E=[...m,...D];if(!o.filePaths){await w.mkdirp(a.dirname(s));const c={detectionStartTimestamp:i,components:v,stories:E};await w.writeFile(s,JSON.stringify(c))}return{components:v,stories:E}})}async function Re(r,e,t,o){const i=[],s=[];if(o.length===0)return{components:i,stories:s};r.debug(`\u5728\u4E0B\u8FF0\u6587\u4EF6\u4E2D\u67E5\u627E\u7EC4\u4EF6:
3
+ - ${o.map(u=>a.relative(e.rootDir,u)).join(`
4
+ - `)}`);const n=await t.crawlFiles(o);r.debug("\u7EC4\u4EF6\u68C0\u6D4B\u5B8C\u6210");for(const u of n.components)i.push({id:u.id,sourcePosition:u.sourcePosition,exported:u.exported});for(const u of n.stories)s.push({id:u.id,sourcePosition:u.sourcePosition,associatedComponentId:u.associatedComponent?.id||null});return{components:i,stories:s}}async function We(r){const e=a.join(r,"node_modules");let t=0;if(await w.pathExists(e))for(const o of await w.readdir(e)){const i=a.join(e,o),s=await w.lstat(i);(s.isDirectory()||s.isSymbolicLink())&&(t=Math.max(t,s.mtimeMs))}for(const o of se){const i=a.join(r,o);if(await w.pathExists(i)){const s=await w.stat(i);t=Math.max(t,s.mtimeMs)}}return t}async function Ne(r){for(let e=r;;e++)if(await Ie(e))return e}async function Ie(r){return new Promise(e=>{const t=Ce.createServer();t.unref(),t.on("error",()=>e(!1)),t.listen(r,()=>{t.close(()=>{e(!0)})})})}const Te=Z(import.meta.url);async function oe(r,e){const t=a.join(e,"package.json");if(!await w.pathExists(t))return{};const{dependencies:o,devDependencies:i,peerDependencies:s}=JSON.parse(await w.readFile(t,"utf8")),n={...o,...i,...s},u=new Map;for(const[l,p]of Object.entries(n)){let d=0;typeof p=="string"&&(p.startsWith("^")||p.startsWith("~")?d=Number.parseInt(p.slice(1)):d=Number.parseInt(p));const f=async()=>{try{const g=He(l,e);let m=g;for(;m!==a.dirname(m);){const y=a.join(m,"package.json");if(w.existsSync(y)){const D=JSON.parse(await w.readFile(y,"utf8"));if(typeof D.version=="string")return D.version;throw new Error(`\u5305: ${y} \u7684\u7248\u672C\u53F7\u5F02\u5E38`)}m=a.dirname(m)}throw new Error(`\u6839\u636E\u6A21\u5757: ${g} \u7684\u5165\u53E3\u8DEF\u5F84\u65E0\u6CD5\u627E\u5230 package.json`)}catch(g){return r.error(g,`\u65E0\u6CD5\u8BFB\u53D6\u5305: ${l} \u7684\u5B89\u88C5\u7248\u672C, \u4F60\u53EF\u80FD\u6CA1\u6709\u6B63\u786E\u5B89\u88C5\u9879\u76EE\u7684\u4F9D\u8D56\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u3002`),null}};u.set(l,{majorVersion:d,readInstalledVersion:f})}return Object.fromEntries(u)}function He(r,e){try{return Te.resolve(r,{paths:[e]})}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ERR_PACKAGE_PATH_NOT_EXPORTED"){const o=t.message.match(/No "exports" main defined in (.*)(\/|\\)package\.json/);if(o)return o[1]??""}throw t}}function K(r){let e=r;return e.startsWith(`Error: Build failed with 1 error:
5
+ `)&&(e=e.substring(r.indexOf(`
6
+ `)+1)),e.startsWith("Error:")&&(e=e.substring(e.indexOf(":")+1)),e=e.trim(),`<html>
335
7
  <head>
336
8
  <meta http-equiv="refresh" content="3">
337
9
  <style>
@@ -357,57 +29,12 @@ function generateHtmlError(message) {
357
29
  sendPreviewEvent({
358
30
  kind: "error",
359
31
  source: "load",
360
- message: ${JSON.stringify(message)}
32
+ message: ${JSON.stringify(r)}
361
33
  });
362
34
  <\/script>
363
35
  </head>
364
- <body>${escape(message)}</body>
365
- </html>`;
366
- }
367
-
368
- const extensions = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx"]);
369
- const importRegexp = /import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;
370
- function cssModulesWithoutSuffixPlugin() {
371
- return {
372
- name: "previewjs:css-modules-without-suffix",
373
- /**
374
- * 转换代码,为不带有 .module.css 后缀的 CSS 模块导入添加后缀
375
- *
376
- * @param code - 要转换的代码
377
- * @param id - 模块的唯一标识符
378
- * @returns 转换后的代码,如果不需要转换则返回 undefined
379
- */
380
- async transform(code, id) {
381
- const parts = id.split("?");
382
- const _id = parts[0];
383
- if (!_id) {
384
- return;
385
- }
386
- if (!extensions.has(path.extname(_id))) {
387
- return;
388
- }
389
- return code.replace(
390
- importRegexp,
391
- 'import $1 from "$3.$4?$5&.module.css"'
392
- );
393
- }
394
- };
395
- }
396
-
397
- function invalidateStoriesModulesOnUpdate() {
398
- return {
399
- name: "previewjs:invalidate-stories-modules-on-update",
400
- enforce: "post",
401
- /**
402
- * 转换函数,处理代码字符串。
403
- * @param code - 输入的代码字符串。
404
- * @returns 如果代码不包含 `import.meta.hot.accept`,则返回 null;否则返回修改后的代码。
405
- */
406
- transform: (code) => {
407
- if (!code.includes("import.meta.hot.accept(")) {
408
- return null;
409
- }
410
- return `${code}
36
+ <body>${Be(r)}</body>
37
+ </html>`}const Je=new Set([".js",".jsx",".ts",".tsx"]),Le=/import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;function Ve(){return{name:"previewjs:css-modules-without-suffix",async transform(r,e){const t=e.split("?")[0];return!t||!Je.has(a.extname(t))?null:r.replace(Le,'import $1 from "$3.$4?$5&.module.css"')}}}function Ue(){return{name:"previewjs:invalidate-stories-modules-on-update",enforce:"post",transform:r=>r.includes("import.meta.hot.accept(")?`${r}
411
38
  if (import.meta?.hot) {
412
39
  import.meta.hot.accept(newModule => {
413
40
  if (newModule?.default?.component) {
@@ -415,70 +42,11 @@ function invalidateStoriesModulesOnUpdate() {
415
42
  }
416
43
  });
417
44
  }
418
- `;
419
- }
420
- };
421
- }
422
-
423
- function localEval() {
424
- return {
425
- name: "previewjs:local-eval",
426
- enforce: "post",
427
- /**
428
- * 转换代码的钩子函数
429
- * @param code - 输入的代码字符串
430
- * @param id - 文件的唯一标识符
431
- * @returns 如果文件在 node_modules 目录中或包含查询参数,则返回 null;否则返回原始代码加上 PreviewJsEval 函数的代码
432
- */
433
- transform: (code, id) => {
434
- if (id.indexOf("/node_modules/") !== -1) {
435
- return null;
436
- }
437
- if (id.indexOf("?") !== -1) {
438
- return null;
439
- }
440
- return (
441
- // 注意:这是一个大写命名的函数,这样它“看起来像”一个 React 组件。
442
- // 这是为了防止破坏 React Refresh 功能,因为 React Refresh 期望所有导出的都是 React 组件。
443
- `${code}
45
+ `:null}}function Ge(){return{name:"previewjs:local-eval",enforce:"post",transform:(r,e)=>e.indexOf("/node_modules/")!==-1||e.indexOf("?")!==-1?null:`${r}
444
46
  export const PreviewJsEval = (code, args = {}) => {
445
47
  return eval("(({ " + Object.keys(args).join(", ") + "}) => { " + code + " })(args)");
446
48
  }
447
- `
448
- );
449
- }
450
- };
451
- }
452
-
453
- const PATH_PREFIX = "/__previewjs_internal__/preview.js?p=";
454
- function previewScriptPlugin() {
455
- return {
456
- name: "previewjs:preview-script",
457
- /**
458
- * 加载钩子,当 Vite 尝试加载模块时调用
459
- * @param {string} id - 要加载的模块的 ID
460
- * @returns {string | void} - 如果匹配到预览脚本路径,则返回预览脚本的源代码;否则返回 undefined
461
- */
462
- load(id) {
463
- if (!id.startsWith(PATH_PREFIX)) {
464
- return;
465
- }
466
- const base64EncodedOptions = id.substring(PATH_PREFIX.length);
467
- const options = JSON.parse(
468
- Buffer.from(base64EncodedOptions, "base64url").toString("utf8")
469
- );
470
- return previewScriptSource(options);
471
- }
472
- };
473
- }
474
- function previewScriptSource({
475
- previewablePath,
476
- previewableName,
477
- wrapperPath,
478
- wrapperName,
479
- detectedGlobalCssFilePaths
480
- }) {
481
- return `
49
+ `}}const ne="/__previewjs_internal__/preview.js?p=";function ze(){return{name:"previewjs:preview-script",load(r){if(!r.startsWith(ne))return null;const e=r.substring(ne.length),t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return qe(t)}}}function qe({previewablePath:r,previewableName:e,wrapperPath:t,wrapperName:o,detectedGlobalCssFilePaths:i}){return`
482
50
  // \u5BFC\u5165\u521D\u59CB\u5316\u76D1\u542C\u5668\u548C\u9884\u89C8\u7684\u51FD\u6570
483
51
  import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";
484
52
  // \u521D\u59CB\u5316\u76D1\u542C\u5668
@@ -504,7 +72,7 @@ function previewScriptSource({
504
72
  }
505
73
  };
506
74
  // \u76D1\u542C\u53EF\u9884\u89C8\u6A21\u5757\u7684\u70ED\u66F4\u65B0
507
- import.meta.hot.accept(["/${previewablePath}"], ([previewableModule]) => {
75
+ import.meta.hot.accept(["/${r}"], ([previewableModule]) => {
508
76
  if (previewableModule) {
509
77
  refresh({
510
78
  previewableModule,
@@ -512,10 +80,10 @@ function previewScriptSource({
512
80
  }
513
81
  });
514
82
 
515
- ${wrapperPath ? `
516
- const wrapperModulePromise = import(/* @vite-ignore */ "/${wrapperPath}?t=" + Date.now());
83
+ ${t?`
84
+ const wrapperModulePromise = import(/* @vite-ignore */ "/${t}?t=" + Date.now());
517
85
  // \u76D1\u542C\u5305\u88C5\u5668\u6A21\u5757\u7684\u70ED\u66F4\u65B0
518
- import.meta.hot.accept(["/${wrapperPath}"], ([wrapperModule]) => {
86
+ import.meta.hot.accept(["/${t}"], ([wrapperModule]) => {
519
87
  if (wrapperModule) {
520
88
  // \u8C03\u7528\u5237\u65B0\u51FD\u6570\u66F4\u65B0\u9884\u89C8
521
89
  refresh({
@@ -523,13 +91,8 @@ function previewScriptSource({
523
91
  });
524
92
  }
525
93
  });
526
- ` : `
527
- const wrapperModulePromise = Promise.all([${detectedGlobalCssFilePaths.map(
528
- (cssFilePath) => `import(/* @vite-ignore */ "/${cssFilePath.replace(
529
- /\\/g,
530
- "/"
531
- )}").catch(() => null)`
532
- ).join(",")}]).then(() => null);
94
+ `:`
95
+ const wrapperModulePromise = Promise.all([${i.map(s=>`import(/* @vite-ignore */ "/${s.replace(/\\/g,"/")}").catch(() => null)`).join(",")}]).then(() => null);
533
96
  `}
534
97
 
535
98
  // Important: the wrapper must be loaded first as it may monkey-patch
@@ -540,9 +103,9 @@ function previewScriptSource({
540
103
  // \u521D\u59CB\u5316\u9884\u89C8\u5E76\u66F4\u65B0\u5237\u65B0\u51FD\u6570
541
104
  refresh = initPreview({
542
105
  previewableModule,
543
- previewableName: ${JSON.stringify(previewableName)},
106
+ previewableName: ${JSON.stringify(e)},
544
107
  wrapperModule,
545
- wrapperName: ${JSON.stringify(wrapperName)},
108
+ wrapperName: ${JSON.stringify(o)},
546
109
  });
547
110
  });
548
111
  });
@@ -552,7 +115,7 @@ function previewScriptSource({
552
115
  * @returns {Promise<any>} - \u8FD4\u56DE\u4E00\u4E2A Promise\uFF0C\u89E3\u6790\u4E3A\u52A0\u8F7D\u7684\u53EF\u9884\u89C8\u6A21\u5757
553
116
  */
554
117
  function loadFreshPreviewableModule() {
555
- return import(/* @vite-ignore */ "/${previewablePath}?t=" + Date.now());
118
+ return import(/* @vite-ignore */ "/${r}?t=" + Date.now());
556
119
  }
557
120
 
558
121
  /**
@@ -560,1287 +123,6 @@ function previewScriptSource({
560
123
  * @returns {Promise<any>} - \u8FD4\u56DE\u4E00\u4E2A Promise\uFF0C\u89E3\u6790\u4E3A\u52A0\u8F7D\u7684wrapper\u6A21\u5757
561
124
  */
562
125
  function loadFreshWrapperModule() {
563
- return import(/* @vite-ignore */ "/${wrapperPath}?t=" + Date.now());
564
- }
565
- `;
566
- }
567
-
568
- function publicAssetImportPluginPlugin({
569
- rootDir,
570
- publicDir
571
- }) {
572
- return {
573
- name: "previewjs:public-asset-import",
574
- /**
575
- * 解析模块导入路径的钩子函数。
576
- *
577
- * @param source - 导入的源路径
578
- * @param importer - 导入该模块的文件路径
579
- * @returns 如果解析成功,返回解析后的路径;否则返回 undefined
580
- */
581
- resolveId: async (source, importer) => {
582
- if (!importer || !source.startsWith("/") || source.startsWith("/__previewjs__/")) {
583
- return;
584
- }
585
- const publicDirAbsolutePath = path.join(rootDir, publicDir);
586
- const potentialPublicFilePath = path.join(publicDirAbsolutePath, source);
587
- if (!potentialPublicFilePath.startsWith(publicDirAbsolutePath + path.sep)) {
588
- return;
589
- }
590
- if (!await fs$1.pathExists(potentialPublicFilePath)) {
591
- return;
592
- }
593
- return source;
594
- }
595
- };
596
- }
597
-
598
- function toVitePath(absoluteFilePath) {
599
- let _absoluteFilePath = absoluteFilePath;
600
- if (_absoluteFilePath.match(/^[a-z]:/)) {
601
- _absoluteFilePath = _absoluteFilePath[0]?.toUpperCase() + absoluteFilePath.substring(1);
602
- }
603
- return _absoluteFilePath.replace(/\\/g, "/");
604
- }
605
-
606
- const VIRTUAL_PREFIX = "/@cfp-studio-virtual:";
607
- const VIRTUAL_PREFIX2 = "/@id/__x00__";
608
- const jsExtensions = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx"]);
609
- function maybeVirtual(originalId) {
610
- let id = originalId;
611
- if (id.startsWith(VIRTUAL_PREFIX)) {
612
- id = id.slice(VIRTUAL_PREFIX.length);
613
- }
614
- if (id.startsWith("\0")) {
615
- id = id.slice(1);
616
- }
617
- if (id.startsWith(VIRTUAL_PREFIX2)) {
618
- id = id.slice(VIRTUAL_PREFIX2.length);
619
- }
620
- return [id, id !== originalId];
621
- }
622
- function virtualPlugin(options) {
623
- const { reader, rootDir } = options;
624
- return {
625
- name: "previewjs:virtual-fs",
626
- /**
627
- * 解析模块ID。
628
- * 处理虚拟文件的ID解析,判断是否需要将文件视为虚拟文件。
629
- * @param originalId - 原始的模块ID。
630
- * @param originalImporter - 原始的导入者ID。
631
- * @returns 解析后的模块ID,如果不需要处理则返回null。
632
- */
633
- resolveId: async (originalId, originalImporter) => {
634
- const [importer, virtualImporter] = originalImporter ? maybeVirtual(originalImporter) : [null, false];
635
- if (originalId.indexOf("/node_modules/") !== -1) {
636
- return null;
637
- }
638
- let [id] = maybeVirtual(originalId);
639
- id = id.split("?", 2)[0] ?? "";
640
- const extension = path.extname(id);
641
- let absoluteId;
642
- if (path.isAbsolute(id)) {
643
- absoluteId = id;
644
- } else {
645
- if (!importer) {
646
- return null;
647
- }
648
- if (extension && !jsExtensions.has(extension) && extension !== ".svg") {
649
- return path.join(path.dirname(importer), id);
650
- }
651
- absoluteId = path.join(path.dirname(importer), id);
652
- }
653
- const resolved = await resolveAbsoluteModuleId(absoluteId);
654
- if (resolved) {
655
- const [absoluteFilePath] = resolved;
656
- if (await fs$1.pathExists(absoluteFilePath) && !virtualImporter) {
657
- return null;
658
- }
659
- if (!absoluteId.endsWith(extension)) {
660
- absoluteId += extension;
661
- }
662
- const resolvedId = VIRTUAL_PREFIX + absoluteFilePath.replace(/\\/g, "/");
663
- return resolvedId;
664
- }
665
- return null;
666
- },
667
- /**
668
- * 加载模块内容。
669
- * 处理虚拟文件的内容加载,确保只加载允许访问的文件。
670
- * @param id - 模块ID。
671
- * @returns 模块的内容,如果不需要处理则返回null。
672
- */
673
- load: async (id) => {
674
- let _id = id;
675
- if (_id.indexOf("/node_modules/") !== -1) {
676
- return null;
677
- }
678
- if (_id.startsWith(VIRTUAL_PREFIX)) {
679
- _id = _id.slice(VIRTUAL_PREFIX.length);
680
- }
681
- if (_id.startsWith("\0")) {
682
- _id = _id.slice(1);
683
- }
684
- if (_id.startsWith(VIRTUAL_PREFIX2)) {
685
- _id = _id.slice(VIRTUAL_PREFIX2.length);
686
- }
687
- const resolved = await resolveAbsoluteModuleId(_id);
688
- if (!resolved) {
689
- return null;
690
- }
691
- const [absoluteFilePath, entry] = resolved;
692
- let isAllowed = false;
693
- for (const allowedAbsolutePath of options.allowedAbsolutePaths) {
694
- const relativePath = path.relative(
695
- allowedAbsolutePath,
696
- absoluteFilePath
697
- );
698
- if (relativePath && !relativePath.startsWith("..") && !path.isAbsolute(relativePath)) {
699
- isAllowed = true;
700
- break;
701
- }
702
- }
703
- if (!isAllowed) {
704
- options.logger.error(
705
- `\u8BD5\u56FE\u8BBF\u95EE\u7684 ${absoluteFilePath} \u6587\u4EF6\u5728\u8FD0\u884C\u8BBF\u95EE\u7684\u76EE\u5F55\u4E4B\u5916. See https://previewjs.com/docs/config and https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`
706
- );
707
- return null;
708
- }
709
- if (entry.kind !== "file") {
710
- options.logger.error(`Unable to read file from ${absoluteFilePath}`);
711
- return null;
712
- }
713
- const source = await entry.read();
714
- const fileExtension = path.extname(absoluteFilePath);
715
- if (!jsExtensions.has(fileExtension)) {
716
- return source;
717
- }
718
- const moduleExtension = path.extname(id);
719
- return {
720
- code: (
721
- // 对于.js或无扩展名的文件运行esbuild转换,因为可能包含JSX
722
- // 否则,让插件决定是否使用esbuild
723
- !id.includes("__previewjs_internal__") && (moduleExtension === "" || moduleExtension === ".js") ? (await transformWithEsbuild(source, absoluteFilePath, {
724
- loader: absoluteFilePath.endsWith(".ts") ? "ts" : "tsx",
725
- format: "esm",
726
- target: "es2020",
727
- sourcefile: path.relative(rootDir, absoluteFilePath),
728
- ...options.esbuildOptions
729
- })).code : source
730
- )
731
- };
732
- },
733
- /**
734
- * 转换模块代码。
735
- * @param code - 模块代码。
736
- * @param id - 模块ID。
737
- * @returns 转换后的模块代码和源映射,如果不需要处理则返回null。
738
- */
739
- transform: (code, id) => {
740
- if (!id.startsWith(VIRTUAL_PREFIX)) {
741
- return null;
742
- }
743
- return {
744
- code,
745
- map: {
746
- mappings: "",
747
- names: [],
748
- sources: [],
749
- version: 3
750
- }
751
- };
752
- },
753
- /**
754
- * 处理热更新。
755
- * 当文件发生变化时,更新虚拟模块。
756
- * @param context - 热更新上下文。
757
- * @returns 需要更新的模块节点数组,如果不需要处理则返回undefined。
758
- */
759
- handleHotUpdate: async (context) => {
760
- const moduleGraph = options.moduleGraph();
761
- if (!moduleGraph) {
762
- return;
763
- }
764
- const filePath = path.relative(rootDir, context.file);
765
- const absoluteFilePath = path.join(rootDir, filePath);
766
- const entry = await reader.read(absoluteFilePath);
767
- if (!entry || entry.kind !== "file") {
768
- return;
769
- }
770
- const virtualModuleId = VIRTUAL_PREFIX + toVitePath(absoluteFilePath);
771
- const node = moduleGraph.getModuleById(virtualModuleId);
772
- return node && [node];
126
+ return import(/* @vite-ignore */ "/${t}?t=" + Date.now());
773
127
  }
774
- };
775
- async function resolveAbsoluteModuleId(id) {
776
- return await resolveBaseFilePath(id) || await resolveBaseFilePath(path.join(rootDir, id));
777
- }
778
- async function resolveBaseFilePath(baseFilePath) {
779
- for (const suffix of [
780
- "",
781
- ...jsExtensions,
782
- ...[...jsExtensions].map((extension) => `${path.sep}index${extension}`)
783
- ]) {
784
- const absoluteFilePath = `${baseFilePath}${suffix}`;
785
- const entry = await reader.read(absoluteFilePath);
786
- if (entry?.kind === "file") {
787
- return [absoluteFilePath, entry];
788
- }
789
- }
790
- return null;
791
- }
792
- }
793
-
794
- const inspectorServer = () => ({
795
- name: "inspector-server-plugin",
796
- configureServer(server) {
797
- server.middlewares.use(launchEditorMiddleware);
798
- }
799
- });
800
-
801
- var __defProp$2 = Object.defineProperty;
802
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
803
- var __publicField$2 = (obj, key, value) => {
804
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
805
- return value;
806
- };
807
- var __accessCheck = (obj, member, msg) => {
808
- if (!member.has(obj))
809
- throw TypeError("Cannot " + msg);
810
- };
811
- var __privateGet = (obj, member, getter) => {
812
- __accessCheck(obj, member, "read from private field");
813
- return getter ? getter.call(obj) : member.get(obj);
814
- };
815
- var __privateAdd = (obj, member, value) => {
816
- if (member.has(obj))
817
- throw TypeError("Cannot add the same private member more than once");
818
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
819
- };
820
- var __privateSet = (obj, member, value, setter) => {
821
- __accessCheck(obj, member, "write to private field");
822
- setter ? setter.call(obj, value) : member.set(obj, value);
823
- return value;
824
- };
825
- var _state, _exclusively, _readerListener;
826
- const POSTCSS_CONFIG_FILE = [
827
- ".postcssrc",
828
- ".postcssrc.json",
829
- ".postcssrc.yml",
830
- ".postcssrc.js",
831
- ".postcssrc.mjs",
832
- ".postcssrc.cjs",
833
- ".postcssrc.ts",
834
- "postcss.config.js",
835
- "postcss.config.mjs",
836
- "postcss.config.cjs",
837
- "postcss.config.ts"
838
- ];
839
- const GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT = [
840
- "index",
841
- "global",
842
- "globals",
843
- "style",
844
- "styles",
845
- "app"
846
- ];
847
- const GLOBAL_CSS_EXTS = ["css", "sass", "scss", "less", "styl", "stylus"];
848
- const GLOBAL_CSS_FILE = GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT.flatMap(
849
- (fileName) => GLOBAL_CSS_EXTS.map((ext) => `${fileName}.${ext}`)
850
- );
851
- const FILES_REQUIRING_VITE_RESTART = /* @__PURE__ */ new Set([
852
- ...PREVIEW_CONFIG_NAMES,
853
- ...FILES_REQUIRING_REDETECTION,
854
- ...POSTCSS_CONFIG_FILE,
855
- ...GLOBAL_CSS_FILE,
856
- "vite.config.js",
857
- "vite.config.ts",
858
- // TODO: Make plugins contribute files requiring restart to make core agnostic of Svelte config files.
859
- "svelte.config.js"
860
- ]);
861
- async function endState(state) {
862
- if (state?.kind === "starting") {
863
- return state.promise;
864
- }
865
- return state;
866
- }
867
- class ViteManager {
868
- constructor(options) {
869
- this.options = options;
870
- __publicField$2(this, "middleware");
871
- __privateAdd(this, _state, null);
872
- __privateAdd(this, _exclusively, void 0);
873
- __privateAdd(this, _readerListener, {
874
- onChange: (absoluteFilePath, info) => {
875
- this.onFileChanged(path.resolve(absoluteFilePath), info).catch(
876
- (e) => this.options.logger.error(e)
877
- );
878
- }
879
- });
880
- const router = express.Router();
881
- router.use(async (req, res, next) => {
882
- const state = await endState(__privateGet(this, _state));
883
- if (!state || state.kind === "error") {
884
- return next();
885
- }
886
- try {
887
- state.viteServer.middlewares(req, res, next);
888
- } catch (e) {
889
- this.options.logger.error(`Vite middleware error: ${e}`);
890
- res.status(500).end(`Vite middleware error: ${e}`);
891
- }
892
- });
893
- this.middleware = router;
894
- __privateSet(this, _exclusively, exclusivePromiseRunner());
895
- }
896
- get state() {
897
- return __privateGet(this, _state);
898
- }
899
- async loadIndexHtml(url, id) {
900
- return __privateGet(this, _exclusively).call(this, async () => {
901
- try {
902
- const state = await endState(__privateGet(this, _state));
903
- if (!state) {
904
- return generateHtmlError("Vite server is not running");
905
- }
906
- if (state.kind === "error") {
907
- return generateHtmlError(state.error);
908
- }
909
- const template = await fs$1.readFile(
910
- this.options.shadowHtmlFilePath,
911
- "utf-8"
912
- );
913
- const { config, viteServer } = state;
914
- const { filePath, name: previewableName } = decodePreviewableId(id);
915
- const previewablePath = filePath.replace(/\\/g, "/");
916
- const wrapper = config.wrapper;
917
- const wrapperPath = wrapper && await fs$1.pathExists(path.join(this.options.rootDir, wrapper.path)) ? wrapper.path.replace(/\\/g, "/") : null;
918
- return await viteServer.transformIndexHtml(
919
- url,
920
- // 将占位符替换为实际内容, 注入 iframe/preview/__previewjs_internal__/preview.js
921
- // 将参数进行 base64 编码, 以 url 参数形式传递到 script 标签中
922
- template.replace(
923
- "<!-- %OPTIONAL_HEAD_CONTENT% -->",
924
- `<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(
925
- JSON.stringify({
926
- previewablePath,
927
- previewableName,
928
- wrapperPath,
929
- wrapperName: wrapper?.componentName || null,
930
- detectedGlobalCssFilePaths: config.detectedGlobalCssFilePaths
931
- }),
932
- "utf8"
933
- ).toString("base64url")}"><\/script>`
934
- )
935
- );
936
- } catch (e) {
937
- return generateHtmlError(`${e}`);
938
- }
939
- });
940
- }
941
- // Note: this is guaranteed not to throw.
942
- async start() {
943
- let setEndState;
944
- __privateSet(this, _state, {
945
- kind: "starting",
946
- promise: new Promise((resolve) => {
947
- setEndState = (state) => {
948
- __privateSet(this, _state, state);
949
- resolve(state);
950
- };
951
- })
952
- });
953
- this.options.reader.listeners.add(__privateGet(this, _readerListener));
954
- try {
955
- process.chdir(this.options.rootDir);
956
- const configFromProject = await readConfig(
957
- this.options.rootDir,
958
- viteLogLevelFromPinoLogger(this.options.logger)
959
- );
960
- const globalCssAbsoluteFilePaths = await findFiles(
961
- this.options.rootDir,
962
- `**/@(${GLOBAL_CSS_FILE_NAMES_WITHOUT_EXT.join(
963
- "|"
964
- )}).@(${GLOBAL_CSS_EXTS.join("|")})`,
965
- {
966
- maxDepth: 3
967
- }
968
- );
969
- const config = {
970
- ...configFromProject,
971
- wrapper: configFromProject.wrapper || {
972
- path: this.options.frameworkPlugin.defaultWrapperPath
973
- },
974
- detectedGlobalCssFilePaths: globalCssAbsoluteFilePaths.map(
975
- (absoluteFilePath) => path.relative(this.options.rootDir, absoluteFilePath)
976
- )
977
- };
978
- const tsInferredAlias = [];
979
- let tsConfig = null;
980
- for (const potentialTsConfigFileName of [
981
- "tsconfig.json",
982
- "jsconfig.json"
983
- ]) {
984
- const potentialTsConfigFilePath = path.join(
985
- this.options.rootDir,
986
- potentialTsConfigFileName
987
- );
988
- try {
989
- if (await fs$1.pathExists(potentialTsConfigFilePath)) {
990
- const unsafeTsConfig = loadTsconfig(potentialTsConfigFilePath) || null;
991
- if (unsafeTsConfig) {
992
- tsConfig = validTsConfig.parse(unsafeTsConfig);
993
- break;
994
- }
995
- }
996
- } catch (e) {
997
- this.options.logger.warn(
998
- `Unable to load tsconfig from ${potentialTsConfigFilePath}: ${e}`
999
- );
1000
- }
1001
- }
1002
- this.options.logger.debug(
1003
- `Loaded ts/jsconfig: ${JSON.stringify(tsConfig || null, null, 2)}`
1004
- );
1005
- const baseUrl = tsConfig?.compilerOptions?.baseUrl || "";
1006
- const tsConfigPaths = tsConfig?.compilerOptions?.paths || {};
1007
- let baseAlias = baseUrl.startsWith("./") ? baseUrl.substring(1) : baseUrl;
1008
- if (baseAlias && !baseAlias.endsWith("/")) {
1009
- baseAlias += "/";
1010
- }
1011
- for (const [match, mapping] of Object.entries(tsConfigPaths)) {
1012
- const firstMapping = mapping[0];
1013
- if (!firstMapping) {
1014
- continue;
1015
- }
1016
- const matchNoWildcard = match.endsWith("/*") ? match.slice(0, match.length - 2) : match;
1017
- const firstMappingNoWildcard = firstMapping.endsWith("/*") ? firstMapping.slice(0, firstMapping.length - 2) : firstMapping;
1018
- tsInferredAlias.push({
1019
- find: matchNoWildcard,
1020
- replacement: path.join(
1021
- this.options.rootDir,
1022
- baseUrl,
1023
- firstMappingNoWildcard
1024
- )
1025
- });
1026
- }
1027
- const existingViteConfig = await vite.loadConfigFromFile(
1028
- {
1029
- command: "serve",
1030
- mode: "development"
1031
- },
1032
- void 0,
1033
- this.options.rootDir
1034
- );
1035
- const defaultLogger = vite.createLogger(
1036
- viteLogLevelFromPinoLogger(this.options.logger)
1037
- );
1038
- const frameworkPluginViteConfig = this.options.frameworkPlugin.viteConfig(
1039
- await flattenPlugins([
1040
- ...existingViteConfig?.config.plugins || [],
1041
- ...config.vite?.plugins || []
1042
- ])
1043
- );
1044
- const publicDir = config.vite?.publicDir || existingViteConfig?.config.publicDir || frameworkPluginViteConfig.publicDir || config.publicDir || "public";
1045
- const plugins = replaceHandleHotUpdate(
1046
- this.options.reader,
1047
- await flattenPlugins([
1048
- viteTsconfigPaths({
1049
- root: this.options.rootDir
1050
- }),
1051
- previewScriptPlugin(),
1052
- virtualPlugin({
1053
- logger: this.options.logger,
1054
- reader: this.options.reader,
1055
- rootDir: this.options.rootDir,
1056
- allowedAbsolutePaths: config.vite?.server?.fs?.allow || existingViteConfig?.config.server?.fs?.allow || [
1057
- searchForWorkspaceRoot(this.options.rootDir)
1058
- ],
1059
- moduleGraph: () => {
1060
- if (__privateGet(this, _state)?.kind === "running") {
1061
- return __privateGet(this, _state).viteServer.moduleGraph;
1062
- }
1063
- return null;
1064
- },
1065
- esbuildOptions: frameworkPluginViteConfig.esbuild || {}
1066
- }),
1067
- localEval(),
1068
- inspectorServer(),
1069
- // 增加react-inspector-plugin插件
1070
- invalidateStoriesModulesOnUpdate(),
1071
- fakeExportedTypesPlugin({
1072
- readFile: (absoluteFilePath) => this.options.reader.read(absoluteFilePath).then((entry) => {
1073
- if (entry?.kind !== "file") {
1074
- return null;
1075
- }
1076
- return entry.read();
1077
- })
1078
- }),
1079
- // forced cast rollup.plugin to vite.plugin
1080
- cssModulesWithoutSuffixPlugin(),
1081
- publicAssetImportPluginPlugin({
1082
- rootDir: this.options.rootDir,
1083
- publicDir
1084
- }),
1085
- frameworkPluginViteConfig.plugins
1086
- ])
1087
- );
1088
- this.options.logger.debug("Creating Vite server");
1089
- const viteServerPromise = vite.createServer({
1090
- ...frameworkPluginViteConfig,
1091
- ...existingViteConfig?.config,
1092
- ...config.vite,
1093
- configFile: false,
1094
- root: this.options.rootDir,
1095
- server: {
1096
- middlewareMode: true,
1097
- hmr: {
1098
- overlay: false,
1099
- server: this.options.server,
1100
- clientPort: this.options.clientPort || this.options.port,
1101
- ...typeof config.vite?.server?.hmr === "object" ? config.vite?.server?.hmr : {}
1102
- },
1103
- fs: {
1104
- strict: false,
1105
- ...config.vite?.server?.fs || {}
1106
- },
1107
- ...config.vite?.server
1108
- },
1109
- customLogger: {
1110
- info: defaultLogger.info,
1111
- warn: defaultLogger.warn,
1112
- error: (msg, options) => {
1113
- if (!msg.startsWith("\x1B[31mInternal server error")) {
1114
- if (__privateGet(this, _state)?.kind === "running") {
1115
- __privateGet(this, _state).viteServer.ws.send({
1116
- type: "error",
1117
- err: {
1118
- message: msg,
1119
- stack: ""
1120
- }
1121
- });
1122
- }
1123
- }
1124
- defaultLogger.error(msg, options);
1125
- },
1126
- warnOnce: defaultLogger.warnOnce,
1127
- clearScreen: () => {
1128
- },
1129
- hasWarned: defaultLogger.hasWarned,
1130
- hasErrorLogged: defaultLogger.hasErrorLogged
1131
- },
1132
- clearScreen: false,
1133
- cacheDir: config.vite?.cacheDir || existingViteConfig?.config.cacheDir || this.options.cacheDir,
1134
- publicDir,
1135
- plugins,
1136
- define: {
1137
- __filename: void 0,
1138
- __dirname: void 0,
1139
- process: void 0,
1140
- ...frameworkPluginViteConfig.define,
1141
- ...existingViteConfig?.config.define,
1142
- ...config.vite?.define
1143
- },
1144
- resolve: {
1145
- ...existingViteConfig?.config.resolve,
1146
- ...config.vite?.resolve,
1147
- alias: [
1148
- // First defined rules are applied first, therefore highest priority should come first.
1149
- ...viteAliasToRollupAliasEntries(config.vite?.resolve?.alias),
1150
- ...viteAliasToRollupAliasEntries(config.alias),
1151
- ...viteAliasToRollupAliasEntries(
1152
- existingViteConfig?.config.resolve?.alias
1153
- ),
1154
- ...tsInferredAlias,
1155
- {
1156
- find: /^~(.*)/,
1157
- replacement: `${baseAlias}$1`
1158
- },
1159
- {
1160
- find: "@",
1161
- replacement: baseAlias
1162
- },
1163
- ...viteAliasToRollupAliasEntries(
1164
- frameworkPluginViteConfig.resolve?.alias
1165
- )
1166
- ]
1167
- }
1168
- });
1169
- const viteServer = await viteServerPromise;
1170
- setEndState({
1171
- kind: "running",
1172
- config,
1173
- viteServer
1174
- });
1175
- this.options.logger.debug("Done starting Vite server");
1176
- } catch (e) {
1177
- this.options.logger.error(`Vite startup error: ${e}`);
1178
- setEndState({
1179
- kind: "error",
1180
- error: e.stack || e.message
1181
- });
1182
- }
1183
- return __privateGet(this, _state).promise;
1184
- }
1185
- async stop({ restart } = { restart: false }) {
1186
- await __privateGet(this, _exclusively).call(this, async () => {
1187
- this.options.reader.listeners.remove(__privateGet(this, _readerListener));
1188
- const state = await endState(__privateGet(this, _state));
1189
- if (state?.kind === "running") {
1190
- await state.viteServer.close();
1191
- }
1192
- if (restart) {
1193
- return this.start();
1194
- }
1195
- return __privateSet(this, _state, null);
1196
- });
1197
- }
1198
- async onFileChanged(absoluteFilePath, info) {
1199
- const state = await endState(this.state);
1200
- if (!state) {
1201
- return;
1202
- }
1203
- if (!info.virtual) {
1204
- this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(
1205
- path.relative(this.options.rootDir, absoluteFilePath)
1206
- );
1207
- if (FILES_REQUIRING_VITE_RESTART.has(path.basename(absoluteFilePath))) {
1208
- this.options.logger.info(
1209
- "New dependencies were detected. Restarting..."
1210
- );
1211
- await this.stop({ restart: true });
1212
- return;
1213
- }
1214
- }
1215
- if (state.kind !== "running") {
1216
- return;
1217
- }
1218
- const { viteServer, config } = state;
1219
- if (info.virtual) {
1220
- const modules = await viteServer.moduleGraph.getModulesByFile(
1221
- toVitePath(absoluteFilePath)
1222
- );
1223
- for (const module of modules || []) {
1224
- if (!module.id) {
1225
- continue;
1226
- }
1227
- try {
1228
- const loaded = await viteServer.pluginContainer.load(module.id);
1229
- if (!loaded) {
1230
- continue;
1231
- }
1232
- const source = typeof loaded === "object" ? loaded.code : loaded;
1233
- await viteServer.pluginContainer.transform(source, module.id);
1234
- } catch {
1235
- return;
1236
- }
1237
- }
1238
- for (const onChange of viteServer.watcher.listeners("change")) {
1239
- onChange(absoluteFilePath);
1240
- }
1241
- } else if (config.wrapper && absoluteFilePath === path.resolve(this.options.rootDir, config.wrapper.path)) {
1242
- viteServer.moduleGraph.invalidateAll();
1243
- viteServer.ws.send({
1244
- type: "full-reload"
1245
- });
1246
- }
1247
- }
1248
- }
1249
- _state = new WeakMap();
1250
- _exclusively = new WeakMap();
1251
- _readerListener = new WeakMap();
1252
- function viteAliasToRollupAliasEntries(alias) {
1253
- if (!alias) {
1254
- return [];
1255
- }
1256
- if (Array.isArray(alias)) {
1257
- return alias;
1258
- }
1259
- return Object.entries(alias).map(([find, replacement]) => ({
1260
- find,
1261
- replacement
1262
- }));
1263
- }
1264
- async function flattenPlugins(pluginOptions) {
1265
- const plugins = [];
1266
- for (const pluginOption of await Promise.all(pluginOptions)) {
1267
- if (!pluginOption) {
1268
- continue;
1269
- }
1270
- if (Array.isArray(pluginOption)) {
1271
- plugins.push(...await flattenPlugins(pluginOption));
1272
- } else {
1273
- plugins.push(pluginOption);
1274
- }
1275
- }
1276
- return plugins;
1277
- }
1278
- function viteLogLevelFromPinoLogger(logger) {
1279
- switch (logger.level) {
1280
- case "fatal":
1281
- return "silent";
1282
- case "error":
1283
- return "error";
1284
- case "warn":
1285
- return "warn";
1286
- case "info":
1287
- return "info";
1288
- case "debug":
1289
- return "info";
1290
- case "trace":
1291
- return "info";
1292
- case "silent":
1293
- return "silent";
1294
- default:
1295
- logger.warn(`Unknown log level: ${logger.level}`);
1296
- return "info";
1297
- }
1298
- }
1299
- function replaceHandleHotUpdate(reader, plugins) {
1300
- return plugins.map(async (plugin) => {
1301
- if (!plugin.handleHotUpdate) {
1302
- return plugin;
1303
- }
1304
- const handleHotUpdate = typeof plugin.handleHotUpdate === "function" ? plugin.handleHotUpdate : plugin.handleHotUpdate.handler;
1305
- return {
1306
- ...plugin,
1307
- handleHotUpdate: async (ctx) => {
1308
- await handleHotUpdate({
1309
- ...ctx,
1310
- read: async () => {
1311
- const entry = await reader.read(ctx.file);
1312
- if (entry?.kind !== "file") {
1313
- return ctx.read();
1314
- }
1315
- return entry.read();
1316
- }
1317
- });
1318
- }
1319
- };
1320
- });
1321
- }
1322
- const validTsConfig = z.object({
1323
- compilerOptions: z.object({
1324
- baseUrl: z.string().optional(),
1325
- paths: z.record(z.array(z.string())).optional()
1326
- }).optional()
1327
- });
1328
-
1329
- var __defProp$1 = Object.defineProperty;
1330
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1331
- var __publicField$1 = (obj, key, value) => {
1332
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1333
- return value;
1334
- };
1335
- class Previewer {
1336
- constructor(options) {
1337
- this.options = options;
1338
- __publicField$1(this, "transformingReader");
1339
- __publicField$1(this, "viteManager", null);
1340
- __publicField$1(this, "status", { kind: "stopped" });
1341
- __publicField$1(this, "disposeObserver", null);
1342
- this.transformingReader = createStackedReader([
1343
- options.reader,
1344
- createFileSystemReader({
1345
- mapping: {
1346
- from: options.frameworkPlugin.previewDirPath,
1347
- to: path.join(options.rootDir, "__previewjs_internal__", "renderer")
1348
- },
1349
- watch: false
1350
- }),
1351
- createFileSystemReader({
1352
- mapping: {
1353
- from: options.previewDirPath,
1354
- to: options.rootDir
1355
- },
1356
- watch: false
1357
- })
1358
- ]);
1359
- }
1360
- /**
1361
- * 启动预览服务器。
1362
- * 如果预览服务器已经在启动中,该方法将等待启动完成。
1363
- * 如果预览服务器已经启动,该方法将立即返回。
1364
- * 如果预览服务器已经在停止中,该方法将等待停止完成,然后重新启动。
1365
- * 如果预览服务器已经停止,该方法将启动预览服务器。
1366
- */
1367
- async start() {
1368
- const statusBeforeStart = this.status;
1369
- switch (statusBeforeStart.kind) {
1370
- case "starting":
1371
- try {
1372
- await statusBeforeStart.promise;
1373
- } catch (e) {
1374
- this.options.logger.error(e);
1375
- this.status = {
1376
- kind: "stopped"
1377
- };
1378
- await this.startFromStopped();
1379
- }
1380
- break;
1381
- case "started":
1382
- break;
1383
- case "stopping":
1384
- try {
1385
- await statusBeforeStart.promise;
1386
- } catch (e) {
1387
- this.options.logger.error(e);
1388
- this.status = {
1389
- kind: "stopped"
1390
- };
1391
- }
1392
- await this.start();
1393
- break;
1394
- case "stopped":
1395
- await this.startFromStopped();
1396
- break;
1397
- default:
1398
- throw assertNever(statusBeforeStart);
1399
- }
1400
- }
1401
- /**
1402
- * 从停止状态启动
1403
- */
1404
- async startFromStopped() {
1405
- this.status = {
1406
- kind: "starting",
1407
- promise: (async () => {
1408
- const router = express.Router();
1409
- router.use((_req, res, next) => {
1410
- res.setHeader("Cache-Control", "max-age=0, must-revalidate");
1411
- next();
1412
- });
1413
- router.use(this.options.middlewares);
1414
- router.get(/^\/.*:[^/]+\/$/, async (req, res, next) => {
1415
- const accept = req.header("Accept");
1416
- if (req.url.includes("?html-proxy")) {
1417
- next();
1418
- return;
1419
- }
1420
- if (accept === "text/x-vite-ping") {
1421
- res.writeHead(204).end();
1422
- return;
1423
- }
1424
- const previewableId = req.path.substring(1, req.path.length - 1);
1425
- if (!this.viteManager) {
1426
- res.status(404).end("Vite\u670D\u52A1\u5668\u672A\u542F\u52A8");
1427
- return;
1428
- }
1429
- res.status(200).set({ "Content-Type": "text/html" }).end(
1430
- await this.viteManager.loadIndexHtml(
1431
- req.originalUrl,
1432
- previewableId
1433
- )
1434
- );
1435
- });
1436
- router.use("/ping", async (req, res) => {
1437
- res.json(
1438
- JSON.stringify({
1439
- pong: "match!"
1440
- })
1441
- );
1442
- });
1443
- router.use((req, res, next) => {
1444
- this.viteManager?.middleware(req, res, next);
1445
- });
1446
- if (this.transformingReader.observe) {
1447
- try {
1448
- this.disposeObserver = await this.transformingReader.observe(
1449
- this.options.rootDir
1450
- );
1451
- } catch (error) {
1452
- this.options.logger.error("\u542F\u52A8\u6587\u4EF6\u7CFB\u7EDF\u76D1\u542C\u5931\u8D25:", error);
1453
- }
1454
- }
1455
- const { server, disposeHttpServer } = await this.options.getHttpServer(
1456
- router
1457
- );
1458
- this.options.logger.debug("\u542F\u52A8 Vite manager ...");
1459
- this.viteManager = new ViteManager({
1460
- rootDir: this.options.rootDir,
1461
- shadowHtmlFilePath: path.join(
1462
- this.options.previewDirPath,
1463
- "index.html"
1464
- ),
1465
- reader: this.transformingReader,
1466
- cacheDir: path.join(getCacheDir(this.options.rootDir), "vite"),
1467
- logger: this.options.logger,
1468
- frameworkPlugin: this.options.frameworkPlugin,
1469
- server,
1470
- port: this.options.port,
1471
- clientPort: this.options.clientPort
1472
- });
1473
- this.viteManager.start();
1474
- this.options.logger.debug("\u9884\u89C8\u670D\u52A1\u5DF2\u5C31\u7EEA");
1475
- this.status = {
1476
- kind: "started",
1477
- onStop: disposeHttpServer
1478
- };
1479
- })()
1480
- };
1481
- await this.status.promise;
1482
- for (let i = 0; ; i++) {
1483
- try {
1484
- await axios.get(`http://localhost:${this.options.port}`);
1485
- break;
1486
- } catch (e) {
1487
- if (i === 10) {
1488
- throw e;
1489
- }
1490
- await new Promise((resolve) => setTimeout(resolve, 50));
1491
- }
1492
- }
1493
- }
1494
- /**
1495
- * 停止预览服务器
1496
- * @returns
1497
- */
1498
- async stop() {
1499
- if (this.status.kind === "starting") {
1500
- try {
1501
- await this.status.promise;
1502
- } catch {
1503
- this.status = {
1504
- kind: "stopped"
1505
- };
1506
- }
1507
- }
1508
- if (this.status.kind !== "started") {
1509
- return;
1510
- }
1511
- const onStop = this.status.onStop;
1512
- this.status = {
1513
- kind: "stopping",
1514
- promise: (async () => {
1515
- await this.disposeObserver?.();
1516
- this.disposeObserver = null;
1517
- await this.viteManager?.stop();
1518
- this.viteManager = null;
1519
- await onStop();
1520
- this.status = {
1521
- kind: "stopped"
1522
- };
1523
- })()
1524
- };
1525
- await this.status.promise;
1526
- }
1527
- }
1528
-
1529
- var __defProp = Object.defineProperty;
1530
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1531
- var __publicField = (obj, key, value) => {
1532
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1533
- return value;
1534
- };
1535
- class ApiRouter {
1536
- /**
1537
- * 构造函数,初始化 ApiRouter 实例。
1538
- * @param logger - 用于记录日志的 Logger 实例。
1539
- */
1540
- constructor(logger) {
1541
- this.logger = logger;
1542
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
1543
- __publicField(this, "handlers", /* @__PURE__ */ new Map());
1544
- /**
1545
- * 注册一个 RPC 端点及其处理函数。
1546
- * @param endpoint - RPC 端点对象。
1547
- * @param handler - 处理该端点请求的函数。
1548
- */
1549
- __publicField(this, "registerRPC", (endpoint, handler) => {
1550
- if (this.handlers.has(endpoint.path)) {
1551
- throw new Error(
1552
- `\u7AEF\u70B9 '${endpoint.path}' \u5DF2\u7ECF\u6CE8\u518C\u4E86 handler\uFF0C\u662F\u5426\u91CD\u590D\u6CE8\u518C\uFF1F`
1553
- );
1554
- }
1555
- this.handlers.set(endpoint.path, handler);
1556
- });
1557
- }
1558
- /**
1559
- * 处理传入的 RPC 请求。
1560
- * @param path - 请求的路径。
1561
- * @param request - 请求的数据。
1562
- * @returns 包含响应结果的包装对象。
1563
- */
1564
- async handle(path, request) {
1565
- const handler = this.handlers.get(path);
1566
- if (!handler) {
1567
- return {
1568
- kind: "error",
1569
- message: `\u8DEF\u5F84 '${path}' \u6CA1\u6709\u6CE8\u518C\u5BF9\u5E94\u7684 handler`
1570
- };
1571
- }
1572
- this.logger.debug(`RPC ${path} invoked`);
1573
- try {
1574
- const response = await handler(request);
1575
- return {
1576
- kind: "success",
1577
- response
1578
- };
1579
- } catch (e) {
1580
- this.logger.error(`RPC ${path} failed: ${e}`);
1581
- if (e instanceof Error) {
1582
- return {
1583
- kind: "error",
1584
- message: e.message
1585
- };
1586
- }
1587
- return {
1588
- kind: "error",
1589
- message: `${e}`
1590
- };
1591
- }
1592
- }
1593
- }
1594
-
1595
- async function findCompatiblePlugin(logger, rootDir, frameworkPlugins) {
1596
- const dependencies = await extractPackageDependencies(logger, rootDir);
1597
- for (const candidate of frameworkPlugins) {
1598
- if (!candidate.info) {
1599
- continue;
1600
- }
1601
- if (await candidate.isCompatible(dependencies)) {
1602
- return candidate.info?.name;
1603
- }
1604
- }
1605
- return null;
1606
- }
1607
-
1608
- const { pino: createLogger } = pino;
1609
- const prettyLogger = PinoPretty;
1610
- const require = createRequire(import.meta.url);
1611
- process.on("uncaughtException", (e) => {
1612
- console.error("Core \u9047\u5230\u672A\u6355\u83B7\u7684\u5F02\u5E38", e);
1613
- });
1614
- process.on("unhandledRejection", (e) => {
1615
- console.error("Core \u9047\u5230\u672A\u5904\u7406\u7684 Promise \u5BF9\u8C61", e);
1616
- });
1617
- async function createWorkspace({
1618
- rootDir,
1619
- frameworkPlugin: frameworkPluginFactory,
1620
- logger = createLogger(
1621
- { level: process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase() || "warn" },
1622
- prettyLogger({ colorize: true })
1623
- ),
1624
- reader = createFileSystemReader(),
1625
- onServerStart = () => Promise.resolve({})
1626
- }) {
1627
- const expectedPluginApiVersion = 5;
1628
- if (!frameworkPluginFactory.info) {
1629
- throw new Error(
1630
- "\u63D0\u4F9B\u7684 framework plugin \u4E0E\u5F53\u524D\u7248\u672C Preview.js \u4E0D\u9002\u914D. \u8BF7\u5347\u7EA7."
1631
- );
1632
- }
1633
- if (frameworkPluginFactory.info.apiVersion > expectedPluginApiVersion) {
1634
- throw new Error(
1635
- `Preview.js \u7684 framework plugin ${frameworkPluginFactory.info.name} \u592A\u65B0\u4E86. \u8BF7\u5347\u7EA7 Preview.js \u6216\u8005\u4F7F\u7528 ${frameworkPluginFactory.info.name} \u7684\u8F83\u65E9\u7248\u672C.`
1636
- );
1637
- }
1638
- const dependencies = await extractPackageDependencies(logger, rootDir);
1639
- if (!await frameworkPluginFactory.isCompatible(dependencies)) {
1640
- throw new Error(
1641
- `Preview.js \u7684 framework plugin ${frameworkPluginFactory.info.name} \u4E0E\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u4F9D\u8D56\u4E0D\u517C\u5BB9\u3002`
1642
- );
1643
- }
1644
- logger.debug(
1645
- `\u4F7F\u7528 ${frameworkPluginFactory.info.name} \u5728\u76EE\u5F55: ${rootDir} \u4E2D\u521B\u5EFA\u5DE5\u4F5C\u533A`
1646
- );
1647
- const frameworkPlugin = await frameworkPluginFactory.create({
1648
- rootDir,
1649
- reader,
1650
- logger,
1651
- dependencies
1652
- });
1653
- const activePreviewers = /* @__PURE__ */ new Set();
1654
- const workspace = {
1655
- frameworkPluginName: frameworkPluginFactory.info.name,
1656
- crawlFiles: frameworkPlugin.crawlFiles,
1657
- typeAnalyzer: frameworkPlugin.typeAnalyzer,
1658
- rootDir,
1659
- reader,
1660
- // 启动预览服务器
1661
- startServer: async ({
1662
- asMiddleware,
1663
- port: maybePort,
1664
- clientPort,
1665
- onStop
1666
- } = {}) => {
1667
- const port = maybePort || await getFreePort(3140);
1668
- const router = new ApiRouter(logger);
1669
- router.registerRPC(RPCs.Analyze, async ({ previewableIds }) => {
1670
- logger.debug(`\u5206\u6790: ${previewableIds.join(", ")}`);
1671
- const detected = await frameworkPlugin.crawlFiles([
1672
- ...new Set(
1673
- previewableIds.map(
1674
- (c) => path.join(rootDir, decodePreviewableId(c).filePath)
1675
- )
1676
- )
1677
- ]);
1678
- logger.debug(
1679
- `\u68C0\u6D4B\u5230 ${detected.components.length} \u4E2A\u7EC4\u4EF6\u548C ${detected.stories.length} \u4E2Astory`
1680
- );
1681
- const previewables = [];
1682
- const idToDetectedComponent = Object.fromEntries(
1683
- detected.components.map((c) => [c.id, c])
1684
- );
1685
- const idToDetectedStory = Object.fromEntries(
1686
- detected.stories.map((c) => [c.id, c])
1687
- );
1688
- let types = {};
1689
- for (const id of previewableIds) {
1690
- const component = idToDetectedComponent[id];
1691
- const story = idToDetectedStory[id];
1692
- let componentTypes;
1693
- if (component) {
1694
- logger.debug(`\u5206\u6790\u7EC4\u4EF6: ${id}`);
1695
- let props;
1696
- ({ props, types: componentTypes } = await component.analyze());
1697
- logger.debug(`\u5B8C\u6210\u7EC4\u4EF6: ${id} \u5206\u6790`);
1698
- previewables.push({
1699
- kind: "component",
1700
- id,
1701
- exported: component.exported,
1702
- sourcePosition: component.sourcePosition,
1703
- props
1704
- });
1705
- } else if (story) {
1706
- let props;
1707
- if (story.associatedComponent) {
1708
- logger.debug(`\u5206\u6790 story: ${id}`);
1709
- ({ props, types: componentTypes } = await story.associatedComponent.analyze());
1710
- logger.debug(`\u5B8C\u6210 story: ${id} \u5206\u6790`);
1711
- } else {
1712
- logger.debug(`story: ${id} \u6CA1\u6709\u5173\u8054\u7684\u7EC4\u4EF6`);
1713
- props = UNKNOWN_TYPE;
1714
- componentTypes = {};
1715
- }
1716
- previewables.push({
1717
- kind: "story",
1718
- id,
1719
- sourcePosition: story.sourcePosition,
1720
- associatedComponentId: story.associatedComponent?.id || null,
1721
- props,
1722
- args: (await story.analyze()).args
1723
- });
1724
- } else {
1725
- const { filePath, name } = decodePreviewableId(id);
1726
- throw new Error(`\u5728 ${filePath} \u4E2D\u672A\u627E\u5230\u7EC4\u4EF6 ${name}. `);
1727
- }
1728
- types = { ...types, ...componentTypes };
1729
- }
1730
- return {
1731
- previewables,
1732
- types
1733
- };
1734
- });
1735
- router.registerRPC(RPCs.GetInfo, async () => ({
1736
- frameworkPlugin: frameworkPluginFactory.info
1737
- }));
1738
- router.registerRPC(
1739
- RPCs.CrawlFiles,
1740
- (options) => crawlFiles(logger, workspace, frameworkPlugin, options)
1741
- );
1742
- const middlewares = [
1743
- // 0. 增加cors能力
1744
- cors(),
1745
- // 1. 处理 JSON 请求
1746
- express.json(),
1747
- // 2. 处理 URL 编码的请求
1748
- async (req, res, next) => {
1749
- if (req.path.startsWith("/api/")) {
1750
- res.json(await router.handle(req.path.substr(5), req.body));
1751
- } else {
1752
- next();
1753
- }
1754
- }
1755
- ];
1756
- if (onServerStart) {
1757
- const { middlewares: additionalMiddlewares = [] } = await onServerStart(
1758
- {
1759
- registerRPC: (endpoint, handler) => router.registerRPC(endpoint, handler),
1760
- workspace
1761
- }
1762
- );
1763
- middlewares.push(...additionalMiddlewares);
1764
- }
1765
- const getHttpServer = asMiddleware ? async (router2) => {
1766
- const unregister = asMiddleware.register(router2);
1767
- return {
1768
- server: asMiddleware.server,
1769
- disposeHttpServer: async () => {
1770
- unregister();
1771
- }
1772
- };
1773
- } : async (router2) => {
1774
- logger.debug("\u542F\u52A8 Express \u670D\u52A1\u5668");
1775
- const app = express();
1776
- app.use(router2);
1777
- const server = await new Promise((resolve) => {
1778
- const server2 = app.listen(port, () => {
1779
- logger.info(
1780
- `Preview.js \u9884\u89C8\u670D\u52A1\u8FD0\u884C\u5728 http://localhost:${port}.`
1781
- );
1782
- resolve(server2);
1783
- });
1784
- });
1785
- const serverTerminator = createHttpTerminator({
1786
- server,
1787
- gracefulTerminationTimeout: 0
1788
- });
1789
- return {
1790
- server,
1791
- disposeHttpServer: async () => {
1792
- await serverTerminator.terminate();
1793
- logger.info("Preview.js \u9884\u89C8\u670D\u52A1\u5668\u5DF2\u505C\u6B62.");
1794
- }
1795
- };
1796
- };
1797
- const previewer = new Previewer({
1798
- reader,
1799
- rootDir,
1800
- // TODO: Use a cleaner approach.
1801
- previewDirPath: path.join(
1802
- path.dirname(path.dirname(require.resolve("@cfp-studio/iframe"))),
1803
- "preview"
1804
- ),
1805
- frameworkPlugin,
1806
- logger,
1807
- middlewares,
1808
- getHttpServer,
1809
- port,
1810
- clientPort
1811
- });
1812
- await previewer.start();
1813
- activePreviewers.add(previewer);
1814
- return {
1815
- port,
1816
- // 服务器端口号
1817
- stop: async () => {
1818
- activePreviewers.delete(previewer);
1819
- await previewer.stop();
1820
- await onStop?.();
1821
- }
1822
- };
1823
- },
1824
- // 清理工作区资源
1825
- dispose: async () => {
1826
- await Promise.all(
1827
- [...activePreviewers].map((previewer) => previewer.stop())
1828
- );
1829
- activePreviewers.clear();
1830
- frameworkPlugin.dispose();
1831
- }
1832
- };
1833
- return workspace;
1834
- }
1835
- function findWorkspaceRoot(absoluteFilePath) {
1836
- let dirPath = path.resolve(absoluteFilePath);
1837
- while (dirPath !== path.dirname(dirPath)) {
1838
- if (fs$1.existsSync(path.join(dirPath, "package.json"))) {
1839
- return dirPath;
1840
- }
1841
- dirPath = path.dirname(dirPath);
1842
- }
1843
- return null;
1844
- }
1845
-
1846
- export { createWorkspace, findCompatiblePlugin, findWorkspaceRoot, toVitePath };
128
+ `}function Ke({rootDir:r,publicDir:e}){return{name:"previewjs:public-asset-import",resolveId:async(t,o)=>{if(!o||!t.startsWith("/")||t.startsWith("/__previewjs__/"))return null;const i=a.join(r,e),s=a.join(i,t);return!s.startsWith(i+a.sep)||!await w.pathExists(s)?null:t}}}function Q(r){let e=r;return e.match(/^[a-z]:/)&&(e=e[0]?.toUpperCase()+r.substring(1)),e.replace(/\\/g,"/")}const $="/@cfp-studio-virtual:",W="/@id/__x00__",N=new Set([".js",".jsx",".ts",".tsx"]);function ae(r){let e=r;return e.startsWith($)&&(e=e.slice($.length)),e.startsWith("\0")&&(e=e.slice(1)),e.startsWith(W)&&(e=e.slice(W.length)),[e,e!==r]}function Qe(r){const{reader:e,rootDir:t}=r;return{name:"previewjs:virtual-fs",resolveId:async(s,n)=>{const[u,l]=n?ae(n):[null,!1];if(s.indexOf("/node_modules/")!==-1)return null;let[p]=ae(s);p=p.split("?",2)[0]??"";const d=a.extname(p);let f;if(a.isAbsolute(p))f=p;else{if(!u)return null;if(d&&!N.has(d)&&d!==".svg")return a.join(a.dirname(u),p);f=a.join(a.dirname(u),p)}const g=await o(f);if(g){const[m]=g;return await w.pathExists(m)&&!l?null:(f.endsWith(d)||(f+=d),$+m.replace(/\\/g,"/"))}return null},load:async s=>{let n=s;if(n.indexOf("/node_modules/")!==-1)return null;n.startsWith($)&&(n=n.slice($.length)),n.startsWith("\0")&&(n=n.slice(1)),n.startsWith(W)&&(n=n.slice(W.length));const u=await o(n);if(!u)return null;const[l,p]=u;let d=!1;for(const y of r.allowedAbsolutePaths){const D=a.relative(y,l);if(D&&!D.startsWith("..")&&!a.isAbsolute(D)){d=!0;break}}if(!d)return r.logger.error(`\u8BD5\u56FE\u8BBF\u95EE\u7684 ${l} \u6587\u4EF6\u5728\u8FD0\u884C\u8BBF\u95EE\u7684\u76EE\u5F55\u4E4B\u5916. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(p.kind!=="file")return r.logger.error(`\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6\uFF1A${l}`),null;const f=await p.read(),g=a.extname(l);if(!N.has(g))return f;const m=a.extname(s);return{code:!s.includes("__previewjs_internal__")&&(m===""||m===".js")?(await Ae(f,l,{loader:l.endsWith(".ts")?"ts":"tsx",format:"esm",target:"es2020",sourcefile:a.relative(t,l),...r.esbuildOptions})).code:f}},transform:(s,n)=>n.startsWith($)?{code:s,map:{mappings:"",names:[],sources:[],version:3}}:null,handleHotUpdate:async s=>{const n=r.moduleGraph();if(!n)return null;const u=a.relative(t,s.file),l=a.join(t,u),p=await e.read(l);if(!p||p.kind!=="file")return null;const d=$+Q(l),f=n.getModuleById(d);return f&&[f]}};async function o(s){return await i(s)||await i(a.join(t,s))}async function i(s){for(const n of["",...N,...[...N].map(u=>`${a.sep}index${u}`)]){const u=`${s}${n}`,l=await e.read(u);if(l?.kind==="file")return[u,l]}return null}}const Ye=()=>({name:"inspector-server-plugin",configureServer(r){r.middlewares.use(xe)}});var Xe=Object.defineProperty,Ze=(r,e,t)=>e in r?Xe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,et=(r,e,t)=>(Ze(r,typeof e!="symbol"?e+"":e,t),t),ue=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)},b=(r,e,t)=>(ue(r,e,"read from private field"),t?t.call(r):e.get(r)),Y=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},I=(r,e,t,o)=>(ue(r,e,"write to private field"),o?o.call(r,t):e.set(r,t),t),C,B,T;const tt=[".postcssrc",".postcssrc.json",".postcssrc.yml",".postcssrc.js",".postcssrc.mjs",".postcssrc.cjs",".postcssrc.ts","postcss.config.js","postcss.config.mjs","postcss.config.cjs","postcss.config.ts"],le=["index","global","globals","style","styles","app"],ce=["css","sass","scss","less","styl","stylus"],rt=le.flatMap(r=>ce.map(e=>`${r}.${e}`)),it=new Set([...je,...se,...tt,...rt,"vite.config.js","vite.config.ts","svelte.config.js"]);async function H(r){return r?.kind==="starting"?r.promise:r}class st{constructor(e){this.options=e,et(this,"middleware"),Y(this,C,null),Y(this,B,void 0),Y(this,T,{onChange:(o,i)=>{this.onFileChanged(a.resolve(o),i).catch(s=>this.options.logger.error(s))}});const t=R.Router();t.use(async(o,i,s)=>{const n=await H(b(this,C));if(!n||n.kind==="error")return s();try{n.viteServer.middlewares(o,i,s)}catch(u){this.options.logger.error(`Vite middleware error: ${u}`),i.status(500).end(`Vite middleware error: ${u}`)}}),this.middleware=t,I(this,B,ee())}get state(){return b(this,C)}async loadIndexHtml(e,t){return b(this,B).call(this,async()=>{try{const o=await H(b(this,C));if(!o)return K("Vite server is not running");if(o.kind==="error")return K(o.error);const i=await w.readFile(this.options.shadowHtmlFilePath,"utf-8"),{config:s,viteServer:n}=o,{filePath:u,name:l}=O(t),p=u.replace(/\\/g,"/"),d=s.wrapper,f=d&&await w.pathExists(a.join(this.options.rootDir,d.path))?d.path.replace(/\\/g,"/"):null;return await n.transformIndexHtml(e,i.replace("<!-- %OPTIONAL_HEAD_CONTENT% -->",`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(JSON.stringify({previewablePath:p,previewableName:l,wrapperPath:f,wrapperName:d?.componentName||null,detectedGlobalCssFilePaths:s.detectedGlobalCssFilePaths}),"utf8").toString("base64url")}"><\/script>`))}catch(o){return K(`${o}`)}})}async start(){let e;I(this,C,{kind:"starting",promise:new Promise(t=>{e=o=>{I(this,C,o),t(o)}})}),this.options.reader.listeners.add(b(this,T));try{process.chdir(this.options.rootDir);const t=await $e(this.options.rootDir,pe(this.options.logger)),o=await re(this.options.rootDir,`**/@(${le.join("|")}).@(${ce.join("|")})`,{maxDepth:3}),i={...t,wrapper:t.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:o.map(v=>a.relative(this.options.rootDir,v))},s=[];let n=null;for(const v of["tsconfig.json","jsconfig.json"]){const E=a.join(this.options.rootDir,v);try{if(await w.pathExists(E)){const c=Se(E)||null;if(c){n=nt.parse(c);break}}}catch(c){this.options.logger.warn(`Unable to load tsconfig from ${E}: ${c}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(n||null,null,2)}`);const u=n?.compilerOptions?.baseUrl||"",l=n?.compilerOptions?.paths||{};let p=u.startsWith("./")?u.substring(1):u;p&&!p.endsWith("/")&&(p+="/");for(const[v,E]of Object.entries(l)){const c=E[0];if(!c)continue;const h=v.endsWith("/*")?v.slice(0,v.length-2):v,P=c.endsWith("/*")?c.slice(0,c.length-2):c;s.push({find:h,replacement:a.join(this.options.rootDir,u,P)})}const d=await q.loadConfigFromFile({command:"serve",mode:"development"},void 0,this.options.rootDir),f=q.createLogger(pe(this.options.logger)),g=this.options.frameworkPlugin.viteConfig(await X([...d?.config.plugins||[],...i.vite?.plugins||[]])),m=i.vite?.publicDir||d?.config.publicDir||g.publicDir||i.publicDir||"public",y=ot(this.options.reader,await X([Pe({root:this.options.rootDir}),ze(),Qe({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:i.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[_e(this.options.rootDir)],moduleGraph:()=>b(this,C)?.kind==="running"?b(this,C).viteServer.moduleGraph:null,esbuildOptions:g.esbuild||{}}),Ge(),Ye(),Ue(),ke({readFile:v=>this.options.reader.read(v).then(E=>E?.kind!=="file"?null:E.read())}),Ve(),Ke({rootDir:this.options.rootDir,publicDir:m}),g.plugins]));this.options.logger.debug("Creating Vite server");const D=await q.createServer({...g,...d?.config,...i.vite,configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,hmr:{overlay:!1,server:this.options.server,clientPort:this.options.clientPort||this.options.port,...typeof i.vite?.server?.hmr=="object"?i.vite?.server?.hmr:{}},fs:{strict:!1,...i.vite?.server?.fs||{}},...i.vite?.server},customLogger:{info:f.info,warn:f.warn,error:(v,E)=>{v.startsWith("\x1B[31mInternal server error")||b(this,C)?.kind==="running"&&b(this,C).viteServer.ws.send({type:"error",err:{message:v,stack:""}}),f.error(v,E)},warnOnce:f.warnOnce,clearScreen:()=>{},hasWarned:f.hasWarned,hasErrorLogged:f.hasErrorLogged},clearScreen:!1,cacheDir:i.vite?.cacheDir||d?.config.cacheDir||this.options.cacheDir,publicDir:m,plugins:y,define:{__filename:void 0,__dirname:void 0,process:void 0,...g.define,...d?.config.define,...i.vite?.define},resolve:{...d?.config.resolve,...i.vite?.resolve,alias:[...J(i.vite?.resolve?.alias),...J(i.alias),...J(d?.config.resolve?.alias),...s,{find:/^~(.*)/,replacement:`${p}$1`},{find:"@",replacement:p},...J(g.resolve?.alias)]}});e({kind:"running",config:i,viteServer:D}),this.options.logger.debug("Done starting Vite server")}catch(t){this.options.logger.error(`Vite startup error: ${t}`),e({kind:"error",error:t.stack||t.message})}return b(this,C).promise}async stop({restart:e}={restart:!1}){await b(this,B).call(this,async()=>{this.options.reader.listeners.remove(b(this,T));const t=await H(b(this,C));return t?.kind==="running"&&await t.viteServer.close(),e?this.start():I(this,C,null)})}async onFileChanged(e,t){const o=await H(this.state);if(!o)return;if(!t.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(a.relative(this.options.rootDir,e)),it.has(a.basename(e)))){this.options.logger.info("New dependencies were detected. Restarting..."),await this.stop({restart:!0});return}if(o.kind!=="running")return;const{viteServer:i,config:s}=o;if(t.virtual){const n=await i.moduleGraph.getModulesByFile(Q(e));for(const u of n||[])if(u.id)try{const l=await i.pluginContainer.load(u.id);if(!l)continue;const p=typeof l=="object"?l.code:l;await i.pluginContainer.transform(p,u.id)}catch{return}for(const u of i.watcher.listeners("change"))u(e)}else s.wrapper&&e===a.resolve(this.options.rootDir,s.wrapper.path)&&(i.moduleGraph.invalidateAll(),i.ws.send({type:"full-reload"}))}}C=new WeakMap,B=new WeakMap,T=new WeakMap;function J(r){return r?Array.isArray(r)?r:Object.entries(r).map(([e,t])=>({find:e,replacement:t})):[]}async function X(r){const e=[];for(const t of await Promise.all(r))t&&(Array.isArray(t)?e.push(...await X(t)):e.push(t));return e}function pe(r){switch(r.level){case"fatal":return"silent";case"error":return"error";case"warn":return"warn";case"info":return"info";case"debug":return"info";case"trace":return"info";case"silent":return"silent";default:return r.warn(`Unknown log level: ${r.level}`),"info"}}function ot(r,e){return e.map(async t=>{if(!t.handleHotUpdate)return t;const o=typeof t.handleHotUpdate=="function"?t.handleHotUpdate:t.handleHotUpdate.handler;return{...t,handleHotUpdate:async i=>{await o({...i,read:async()=>{const s=await r.read(i.file);return s?.kind!=="file"?i.read():s.read()}})}}})}const nt=A.object({compilerOptions:A.object({baseUrl:A.string().optional(),paths:A.record(A.array(A.string())).optional()}).optional()});var at=Object.defineProperty,ut=(r,e,t)=>e in r?at(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,L=(r,e,t)=>(ut(r,typeof e!="symbol"?e+"":e,t),t);class lt{constructor(e){this.options=e,L(this,"transformingReader"),L(this,"viteManager",null),L(this,"status",{kind:"stopped"}),L(this,"disposeObserver",null),this.transformingReader=he([e.reader,z({mapping:{from:e.frameworkPlugin.previewDirPath,to:a.join(e.rootDir,"__previewjs_internal__","renderer")},watch:!1}),z({mapping:{from:e.previewDirPath,to:e.rootDir},watch:!1})])}async start(){const e=this.status;switch(e.kind){case"starting":try{await e.promise}catch(t){this.options.logger.error(t),this.status={kind:"stopped"},await this.startFromStopped()}break;case"started":break;case"stopping":try{await e.promise}catch(t){this.options.logger.error(t),this.status={kind:"stopped"}}await this.start();break;case"stopped":await this.startFromStopped();break;default:throw De(e)}}async startFromStopped(){this.status={kind:"starting",promise:(async()=>{const e=R.Router();if(e.use((i,s,n)=>{s.setHeader("Cache-Control","max-age=0, must-revalidate"),n()}),e.use(this.options.middlewares),e.get(/^\/.*:[^/]+\/$/,async(i,s,n)=>{const u=i.header("Accept");if(i.url.includes("?html-proxy")){n();return}if(u==="text/x-vite-ping"){s.writeHead(204).end();return}const l=i.path.substring(1,i.path.length-1);if(!this.viteManager){s.status(404).end("Vite\u670D\u52A1\u5668\u672A\u542F\u52A8");return}s.status(200).set({"Content-Type":"text/html"}).end(await this.viteManager.loadIndexHtml(i.originalUrl,l))}),e.use("/ping",async(i,s)=>{s.json(JSON.stringify({pong:"match!"}))}),e.use((i,s,n)=>{this.viteManager?.middleware(i,s,n)}),this.transformingReader.observe)try{this.disposeObserver=await this.transformingReader.observe(this.options.rootDir)}catch(i){this.options.logger.error(i,"\u542F\u52A8\u6587\u4EF6\u7CFB\u7EDF\u76D1\u542C\u5931\u8D25:")}const{server:t,disposeHttpServer:o}=await this.options.getHttpServer(e);this.options.logger.debug("\u542F\u52A8 Vite manager ..."),this.viteManager=new st({rootDir:this.options.rootDir,shadowHtmlFilePath:a.join(this.options.previewDirPath,"index.html"),reader:this.transformingReader,cacheDir:a.join(te(this.options.rootDir),"vite"),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:t,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug("\u9884\u89C8\u670D\u52A1\u5DF2\u5C31\u7EEA"),this.status={kind:"started",onStop:o}})()},await this.status.promise;for(let e=0;;e++)try{await be.get(`http://localhost:${this.options.port}`);break}catch(t){if(e===10)throw t;await new Promise(o=>setTimeout(o,50))}}async stop(){if(this.status.kind==="starting")try{await this.status.promise}catch{this.status={kind:"stopped"}}if(this.status.kind!=="started")return;const e=this.status.onStop;this.status={kind:"stopping",promise:(async()=>{await this.disposeObserver?.(),this.disposeObserver=null,await this.viteManager?.stop(),this.viteManager=null,await e(),this.status={kind:"stopped"}})()},await this.status.promise}}var ct=Object.defineProperty,pt=(r,e,t)=>e in r?ct(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,de=(r,e,t)=>(pt(r,typeof e!="symbol"?e+"":e,t),t);class dt{constructor(e){this.logger=e,de(this,"handlers",new Map),de(this,"registerRPC",(t,o)=>{if(this.handlers.has(t.path))throw new Error(`\u7AEF\u70B9 '${t.path}' \u5DF2\u7ECF\u6CE8\u518C\u4E86 handler\uFF0C\u662F\u5426\u91CD\u590D\u6CE8\u518C\uFF1F`);this.handlers.set(t.path,o)})}async handle(e,t){const o=this.handlers.get(e);if(!o)return{kind:"error",message:`\u8DEF\u5F84 '${e}' \u6CA1\u6709\u6CE8\u518C\u5BF9\u5E94\u7684 handler`};this.logger.debug(`RPC ${e} invoked`);try{return{kind:"success",response:await o(t)}}catch(i){return this.logger.error(`RPC ${e} failed: ${i}`),i instanceof Error?{kind:"error",message:i.message}:{kind:"error",message:`${i}`}}}}async function ft(r,e,t){const o=await oe(r,e);for(const i of t)if(i.info&&await i.isCompatible(o))return i.info?.name;return null}const{pino:ht}=we,mt=ve,gt=Z(import.meta.url);process.on("uncaughtException",r=>{console.error("Core \u9047\u5230\u672A\u6355\u83B7\u7684\u5F02\u5E38",r)}),process.on("unhandledRejection",r=>{console.error("Core \u9047\u5230\u672A\u5904\u7406\u7684 Promise \u5BF9\u8C61",r)});async function wt({rootDir:r,frameworkPlugin:e,logger:t=ht({level:process.env.PREVIEWJS_LOG_LEVEL?.toLowerCase()||"warn"},mt({colorize:!0})),reader:o=z(),onServerStart:i=()=>Promise.resolve({})}){if(!e.info)throw new Error("\u63D0\u4F9B\u7684 framework plugin \u4E0E\u5F53\u524D\u7248\u672C Preview.js \u4E0D\u9002\u914D. \u8BF7\u5347\u7EA7.");if(e.info.apiVersion>5)throw new Error(`Preview.js \u7684 framework plugin ${e.info.name} \u592A\u65B0\u4E86. \u8BF7\u5347\u7EA7 Preview.js \u6216\u8005\u4F7F\u7528 ${e.info.name} \u7684\u8F83\u65E9\u7248\u672C.`);const s=await oe(t,r);if(!await e.isCompatible(s))throw new Error(`Preview.js \u7684 framework plugin ${e.info.name} \u4E0E\u5F53\u524D\u5DE5\u4F5C\u533A\u7684\u4F9D\u8D56\u4E0D\u517C\u5BB9\u3002`);t.info(`\u4F7F\u7528 ${e.info.name} \u5728\u76EE\u5F55: ${r} \u4E2D\u521B\u5EFA\u5DE5\u4F5C\u533A`);const n=await e.create({rootDir:r,reader:o,logger:t,dependencies:s}),u=new Set,l={frameworkPluginName:e.info.name,crawlFiles:n.crawlFiles,typeAnalyzer:n.typeAnalyzer,rootDir:r,reader:o,startServer:async({asMiddleware:p,port:d,clientPort:f,onStop:g}={})=>{const m=d||await Ne(3140),y=new dt(t);y.registerRPC(G.Analyze,async({previewableIds:c})=>{t.debug(`\u5206\u6790: ${c.join(", ")}`);const h=await n.crawlFiles([...new Set(c.map(F=>a.join(r,O(F).filePath)))]);t.debug(`\u68C0\u6D4B\u5230 ${h.components.length} \u4E2A\u7EC4\u4EF6\u548C ${h.stories.length} \u4E2Astory`);const P=[],V=Object.fromEntries(h.components.map(F=>[F.id,F])),U=Object.fromEntries(h.stories.map(F=>[F.id,F]));let k={};for(const F of c){const x=V[F],S=U[F];let M;if(x){t.debug(`\u5206\u6790\u7EC4\u4EF6: ${F}`);let j;({props:j,types:M}=await x.analyze()),t.debug(`\u5B8C\u6210\u7EC4\u4EF6: ${F} \u5206\u6790`),P.push({kind:"component",id:F,exported:x.exported,sourcePosition:x.sourcePosition,props:j})}else if(S){let j;S.associatedComponent?(t.debug(`\u5206\u6790 story: ${F}`),{props:j,types:M}=await S.associatedComponent.analyze(),t.debug(`\u5B8C\u6210 story: ${F} \u5206\u6790`),t.debug(`props: ${JSON.stringify(j)}`),t.debug(`types: ${JSON.stringify(k)}`)):(t.debug(`story: ${F} \u6CA1\u6709\u5173\u8054\u7684\u7EC4\u4EF6`),j=fe,M={});let _=null;({args:_}=await S.analyze()),P.push({kind:"story",id:F,sourcePosition:S.sourcePosition,associatedComponentId:S.associatedComponent?.id||null,props:j,args:_}),t.debug(`story args: ${JSON.stringify(_)}`)}else{const{filePath:j,name:_}=O(F);throw new Error(`\u5728 ${j} \u4E2D\u672A\u627E\u5230\u7EC4\u4EF6 ${_}. `)}k={...k,...M}}return{previewables:P,types:k}}),y.registerRPC(G.GetInfo,async()=>({frameworkPlugin:e.info})),y.registerRPC(G.CrawlFiles,c=>Oe(t,l,n,c));const D=[me(),R.json(),async(c,h,P)=>{c.path.startsWith("/api/")?h.json(await y.handle(c.path.substr(5),c.body)):P()}];if(i){const{middlewares:c=[]}=await i({registerRPC:(h,P)=>y.registerRPC(h,P),workspace:l});D.push(...c)}const v=p?async c=>{const h=p.register(c);return{server:p.server,disposeHttpServer:async()=>{h()}}}:async c=>{t.debug("\u542F\u52A8 Express \u670D\u52A1\u5668");const h=R();h.use(c);const P=await new Promise(U=>{const k=h.listen(m,()=>{t.info(`Preview.js \u9884\u89C8\u670D\u52A1\u8FD0\u884C\u5728 http://localhost:${m}.`),U(k)})}),V=ge({server:P,gracefulTerminationTimeout:0});return{server:P,disposeHttpServer:async()=>{await V.terminate(),t.info("Preview.js \u9884\u89C8\u670D\u52A1\u5668\u5DF2\u505C\u6B62.")}}},E=new lt({reader:o,rootDir:r,previewDirPath:a.join(a.dirname(a.dirname(gt.resolve("@cfp-studio/iframe"))),"preview"),frameworkPlugin:n,logger:t,middlewares:D,getHttpServer:v,port:m,clientPort:f});return await E.start(),u.add(E),{port:m,stop:async()=>{u.delete(E),await E.stop(),await g?.()}}},dispose:async()=>{await Promise.all([...u].map(p=>p.stop())),u.clear(),n.dispose()}};return l}function vt(r){let e=a.resolve(r);for(;e!==a.dirname(e);){if(w.existsSync(a.join(e,"package.json")))return e;e=a.dirname(e)}return null}export{wt as createWorkspace,ft as findCompatiblePlugin,vt as findWorkspaceRoot,Q as toVitePath};