@cfp-studio/core 1.0.15 → 1.0.16

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.
Files changed (2) hide show
  1. package/dist/index.mjs +7 -7
  2. package/package.json +4 -4
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import{createRequire as e}from"node:module";import t from"node:path";import{createPipelineLogger as n,decodePreviewableId as r}from"@cfp-studio/analyzer-api";import{RPCs as i}from"@cfp-studio/api";import{UNKNOWN_TYPE as a}from"@cfp-studio/type-analyzer";import{createFileSystemReader as o,createStackedReader as s}from"@cfp-studio/vfs";import c from"cors";import l from"express";import u from"fs-extra";import{createHttpTerminator as d}from"http-terminator";import f from"node:fs";import p,{fileURLToPath as m,pathToFileURL as h}from"node:url";import{exclusivePromiseRunner as g}from"exclusive-promises";import{globby as _}from"globby";import v from"node:net";import{assertNever as y}from"assert-never";import b from"axios";import{realpath as x}from"node:fs/promises";import S from"@fwouts/vite-tsconfig-paths";import{loadTsconfig as ee}from"tsconfig-paths/lib/tsconfig-loader.js";import*as C from"vite";import{loadConfigFromFile as te,searchForWorkspaceRoot as ne,transformWithEsbuild as re}from"vite";import{z as w}from"zod";import{escape as ie}from"html-escaper";function T(){return process.env.CFP_BRAND_NAME||`CFP Studio`}function ae(){let e=p.fileURLToPath(new URL(`.`,import.meta.url)),{version:n}=JSON.parse(f.readFileSync(t.resolve(e,`..`,`package.json`),`utf8`));return n}function oe(t,n){let r=e(import.meta.url),i=(()=>{try{let e=r.resolve(`@cfp-studio/type-analyzer/package.json`);return JSON.parse(f.readFileSync(e,`utf8`)).version??`unknown`}catch{return`unknown`}})();return`${t.split(`/`).pop()||`unknown`}@${n}+ta@${i}`}function E(e){try{return t.resolve(e,`node_modules`,`.cfp`,`v${ae()}`)}catch(e){throw Error(`无法获取 @cfp-studio/core 的版本号.\n${e}`)}}function D(e,n,r){return t.join(E(e),`scan-${oe(n,r)}`)}function se(e){let n=t.resolve(e,`node_modules`,`.previewjs`);try{return f.existsSync(n)?(f.rmSync(n,{recursive:!0,force:!0}),!0):!1}catch{return!1}}function ce(e,n,r,i){let a=D(e,n,r),o=t.join(a,`components.json`),s={cacheDir:a,exists:!1,detectionStartTimestamp:null,cachedComponents:0,cachedStories:0,skippedSourceFiles:0,sourceFiles:i.length},c=null;try{if(!f.existsSync(o))return s;c=JSON.parse(f.readFileSync(o,`utf8`))}catch{return{...s,exists:!0}}let l=typeof c?.detectionStartTimestamp==`number`?c.detectionStartTimestamp:0,u=0;for(let e of i)try{f.statSync(e).mtimeMs<l&&(u+=1)}catch{}return{cacheDir:a,exists:!0,detectionStartTimestamp:l||null,cachedComponents:Array.isArray(c?.components)?c.components.length:0,cachedStories:Array.isArray(c?.stories)?c.stories.length:0,skippedSourceFiles:u,sourceFiles:i.length}}function le(e,t,n){let r=D(e,t,n);try{return f.existsSync(r)?(f.rmSync(r,{recursive:!0,force:!0}),!0):!1}catch{return!1}}async function O(e,t,n={}){return k(e,t,{...n,gitignore:!0})}async function k(e,n,r){let i=await de(e),a=t.relative(i,e),o=a?a.split(t.sep).join(`/`)+`/`:``,s=(r.ignoredPaths??[]).map(e=>o+e),c=await _(o+n,{gitignore:r.gitignore,ignore:[`**/node_modules/**`,...s],cwd:i,absolute:!0,followSymbolicLinks:!1,suppressErrors:!0,deep:r.maxDepth}),l=e.replace(/\\/g,`/`);return l.endsWith(`/`)||(l+=`/`),c.filter(e=>e.startsWith(l)).sort()}async function ue(e,t=`**/*.@(js|jsx|ts|tsx|svelte|vue)`,n=[]){let[r,i]=await Promise.all([k(e,t,{ignoredPaths:n,gitignore:!0}),k(e,t,{ignoredPaths:n,gitignore:!1})]),a=new Set(r);return i.filter(e=>!a.has(e))}async function de(e,n=e){try{if(await u.exists(t.join(e,`.git`)))return e;let r=t.dirname(e);return!r||r===e?n:de(r,n)}catch{return n}}const A=new Set([`jsconfig.json`,`tsconfig.json`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`.gitignore`]),fe=g();function j(e,n,i,a={}){return fe(async()=>{e.debug(`开始扫描组件,扫描参数: ${JSON.stringify(a)}`);let o=Date.now(),s=t.join(D(n.rootDir,n.frameworkPluginName,n.frameworkPluginVersion??`unknown`),`components.json`),c=await(async()=>{if(a.filePaths)return a.filePaths.map(e=>t.join(n.rootDir,e));e.debug(`扫描目录: ${n.rootDir},采集可扫描文件`);let r=await O(n.rootDir,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,{ignoredPaths:i.ignoredPaths});return e.debug(`找到 ${r.length} 个包含组件的文件`),r})(),l=new Set(c.map(e=>t.relative(n.rootDir,e).replace(/\\/g,`/`))),d={detectionStartTimestamp:0,components:[],stories:[]};if(u.existsSync(s))try{d=JSON.parse(u.readFileSync(s,`utf8`))}catch{e.warn(`无法转换 ${s} 中存储的缓存信息`)}d.detectionStartTimestamp<await me(n.rootDir)&&(d={detectionStartTimestamp:0,components:[],stories:[]});let f=c.filter(e=>{let t=n.reader.readSync(e);return t?.kind===`file`&&(a.forceRefresh||t.lastModifiedMillis()>=d.detectionStartTimestamp)}),p=new Set(f.map(e=>t.relative(n.rootDir,e).replace(/\\/g,`/`))),m=({id:e})=>{let t=r(e).filePath;return l.has(t)&&!p.has(t)},h=d.components.filter(m),g=d.stories.filter(m),{components:_,stories:v}=await pe(e,n,i,f),y=[...h,..._],b=[...g,...v];if(!a.filePaths){await u.mkdirp(t.dirname(s));let e={detectionStartTimestamp:o,components:y,stories:b};await u.writeFile(s,JSON.stringify(e))}return{components:y,stories:b}})}async function pe(e,n,r,i){let a=[],o=[];if(i.length===0)return{components:a,stories:o};e.debug(`在下述文件中查找组件:\n- ${i.map(e=>t.relative(n.rootDir,e)).join(`
2
- - `)}`);let s=await r.crawlFiles(i);e.debug(`组件检测完成`);for(let e of s.components)a.push({id:e.id,sourcePosition:e.sourcePosition,exported:e.exported});for(let e of s.stories)o.push({id:e.id,sourcePosition:e.sourcePosition,associatedComponentId:e.associatedComponent?.id||null});return{components:a,stories:o}}async function me(e){let n=t.join(e,`node_modules`),r=0;if(await u.pathExists(n))for(let e of await u.readdir(n)){let i=t.join(n,e),a=await u.lstat(i);(a.isDirectory()||a.isSymbolicLink())&&(r=Math.max(r,a.mtimeMs))}for(let n of A){let i=t.join(e,n);if(await u.pathExists(i)){let e=await u.stat(i);r=Math.max(r,e.mtimeMs)}}return r}async function he(e){for(let t=e;;t++)if(await ge(t))return t}async function ge(e){return new Promise(t=>{let n=v.createServer();n.unref(),n.on(`error`,()=>t(!1)),n.listen(e,()=>{n.close(()=>{t(!0)})})})}const _e=e(import.meta.url);async function M(e,n){let r=t.join(n,`package.json`);if(!await u.pathExists(r))return{};let{dependencies:i,devDependencies:a,peerDependencies:o}=JSON.parse(await u.readFile(r,`utf8`)),s={...i,...a,...o},c=new Map;for(let[r,i]of Object.entries(s)){let a=0;typeof i==`string`&&(a=i.startsWith(`^`)||i.startsWith(`~`)?Number.parseInt(i.slice(1)):Number.parseInt(i)),c.set(r,{majorVersion:a,readInstalledVersion:async()=>{try{let e=ve(r,n),i=e;for(;i!==t.dirname(i);){let e=t.join(i,`package.json`);if(u.existsSync(e)){let t=JSON.parse(await u.readFile(e,`utf8`));if(typeof t.version==`string`)return t.version;throw Error(`包: ${e} 的版本号异常`)}i=t.dirname(i)}throw Error(`根据模块: ${e} 的入口路径无法找到 package.json`)}catch(t){return e.error(t,`无法读取包: ${r} 的安装版本, 你可能没有正确安装项目的依赖,请重新安装。`),null}}})}return Object.fromEntries(c)}function ve(e,t){try{return _e.resolve(e,{paths:[t]})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`){let t=e.message.match(/No "exports" main defined in (.*)(\/|\\)package\.json/);if(t)return t[1]??``}throw e}}const N=`/__static`;function ye(e){return async(t,n)=>{let r=await xe(typeof t.query.path==`string`?t.query.path:null,e);if(r.ok===!1){n.status(r.status).type(`text/plain; charset=utf-8`).end(r.message);return}let i;try{i=await f.promises.stat(r.absolutePath)}catch{n.status(404).type(`text/plain; charset=utf-8`).end(`文件不存在`);return}if(!i.isFile()){n.status(404).type(`text/plain; charset=utf-8`).end(`不是文件`);return}n.status(200).type(Se(r.absolutePath)),f.createReadStream(r.absolutePath).on(`error`,()=>{n.destroy()}).pipe(n)}}function P(e,n){let r=t.relative(e,n);return r===``?!0:!r.startsWith(`..`)&&!t.isAbsolute(r)}function be(e,n){if(!t.isAbsolute(e))return{ok:!1};let r=t.resolve(e);for(let e of n)if(P(t.resolve(e),r))return{ok:!0,absolutePath:r};return{ok:!1}}async function xe(e,n,r=x){if(typeof e!=`string`||e.trim()===``)return{ok:!1,status:400,message:`缺少 path 参数`};if(n.length===0)return{ok:!1,status:403,message:`没有可访问的静态目录`};let i=be(e,n);if(!i.ok)return{ok:!1,status:403,message:`该路径不在允许的静态目录内`};let a;try{a=await r(i.absolutePath)}catch{return{ok:!1,status:404,message:`文件不存在`}}return(await Promise.all(n.map(async e=>{try{return await r(t.resolve(e))}catch{return t.resolve(e)}}))).some(e=>P(e,a))?{ok:!0,absolutePath:a}:{ok:!1,status:403,message:`该路径不在允许的静态目录内`}}function Se(e){switch(t.extname(e).toLowerCase()){case`.html`:case`.htm`:return`text/html; charset=utf-8`;case`.css`:return`text/css; charset=utf-8`;case`.js`:case`.mjs`:return`text/javascript; charset=utf-8`;case`.json`:return`application/json; charset=utf-8`;case`.svg`:return`image/svg+xml`;case`.png`:return`image/png`;case`.jpg`:case`.jpeg`:return`image/jpeg`;case`.gif`:return`image/gif`;case`.webp`:return`image/webp`;case`.ico`:return`image/x-icon`;case`.woff`:return`font/woff`;case`.woff2`:return`font/woff2`;case`.txt`:return`text/plain; charset=utf-8`;default:return`application/octet-stream`}}const F=[`preview.config.js`,`preview.config.mjs`,`preview.config.ts`,`preview.config.cjs`,`preview.config.mts`,`preview.config.cts`];async function Ce(e,n){let r={};for(let i of F){let a=t.join(e,i);if(f.existsSync(a))try{let t=await te({command:`serve`,mode:`development`},i,e,n);if(t){r=t.config;break}}catch(e){throw e instanceof Error&&typeof e.message==`string`&&e.message.includes(`config 必须导出或者返回一个对象`)?Error(`请使用一个 preview.config.js 的默认导出`):e}}return r}function I(e){let t=e;return t.startsWith(`Error: Build failed with 1 error:
1
+ import{createRequire as e}from"node:module";import t from"node:path";import{createPipelineLogger as n,decodePreviewableId as r}from"@cfp-studio/analyzer-api";import{RPCs as i}from"@cfp-studio/api";import{UNKNOWN_TYPE as a}from"@cfp-studio/type-analyzer";import{createFileSystemReader as o,createStackedReader as s}from"@cfp-studio/vfs";import c from"cors";import l from"express";import u from"fs-extra";import{createHttpTerminator as d}from"http-terminator";import f from"node:fs";import p,{fileURLToPath as m,pathToFileURL as h}from"node:url";import{exclusivePromiseRunner as g}from"exclusive-promises";import{globby as _}from"globby";import v from"node:net";import{assertNever as y}from"assert-never";import b from"axios";import{realpath as x}from"node:fs/promises";import S from"@fwouts/vite-tsconfig-paths";import{loadTsconfig as C}from"tsconfig-paths/lib/tsconfig-loader.js";import*as w from"vite";import{loadConfigFromFile as ee,searchForWorkspaceRoot as te,transformWithEsbuild as ne}from"vite";import{z as T}from"zod";import{escape as re}from"html-escaper";function E(){return process.env.CFP_BRAND_NAME||`CFP Studio`}function ie(){let e=p.fileURLToPath(new URL(`.`,import.meta.url)),{version:n}=JSON.parse(f.readFileSync(t.resolve(e,`..`,`package.json`),`utf8`));return n}function ae(t,n){let r=e(import.meta.url),i=(()=>{try{let e=r.resolve(`@cfp-studio/type-analyzer/package.json`);return JSON.parse(f.readFileSync(e,`utf8`)).version??`unknown`}catch{return`unknown`}})();return`${t.split(`/`).pop()||`unknown`}@${n}+ta@${i}`}function D(e){try{return t.resolve(e,`node_modules`,`.cfp`,`v${ie()}`)}catch(e){throw Error(`无法获取 @cfp-studio/core 的版本号.\n${e}`)}}function O(e,n,r){return t.join(D(e),`scan-${ae(n,r)}`)}function oe(e){let n=t.resolve(e,`node_modules`,`.previewjs`);try{return f.existsSync(n)?(f.rmSync(n,{recursive:!0,force:!0}),!0):!1}catch{return!1}}function se(e,n,r,i){let a=O(e,n,r),o=t.join(a,`components.json`),s={cacheDir:a,exists:!1,detectionStartTimestamp:null,cachedComponents:0,cachedStories:0,skippedSourceFiles:0,sourceFiles:i.length},c=null;try{if(!f.existsSync(o))return s;c=JSON.parse(f.readFileSync(o,`utf8`))}catch{return{...s,exists:!0}}let l=typeof c?.detectionStartTimestamp==`number`?c.detectionStartTimestamp:0,u=0;for(let e of i)try{f.statSync(e).mtimeMs<l&&(u+=1)}catch{}return{cacheDir:a,exists:!0,detectionStartTimestamp:l||null,cachedComponents:Array.isArray(c?.components)?c.components.length:0,cachedStories:Array.isArray(c?.stories)?c.stories.length:0,skippedSourceFiles:u,sourceFiles:i.length}}function ce(e,t,n){let r=O(e,t,n);try{return f.existsSync(r)?(f.rmSync(r,{recursive:!0,force:!0}),!0):!1}catch{return!1}}async function k(e,t,n={}){return A(e,t,{...n,gitignore:!0})}async function A(e,n,r){let i=await j(e),a=t.relative(i,e),o=a?a.split(t.sep).join(`/`)+`/`:``,s=(r.ignoredPaths??[]).map(e=>o+e),c=await _(o+n,{gitignore:r.gitignore,ignore:[`**/node_modules/**`,...s],cwd:i,absolute:!0,followSymbolicLinks:!1,suppressErrors:!0,deep:r.maxDepth}),l=e.replace(/\\/g,`/`);return l.endsWith(`/`)||(l+=`/`),c.filter(e=>e.startsWith(l)).sort()}async function le(e,t=`**/*.@(js|jsx|ts|tsx|svelte|vue)`,n=[]){let[r,i]=await Promise.all([A(e,t,{ignoredPaths:n,gitignore:!0}),A(e,t,{ignoredPaths:n,gitignore:!1})]),a=new Set(r);return i.filter(e=>!a.has(e))}async function j(e,n=e){try{if(await u.exists(t.join(e,`.git`)))return e;let r=t.dirname(e);return!r||r===e?n:j(r,n)}catch{return n}}const M=new Set([`jsconfig.json`,`tsconfig.json`,`package.json`,`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`.gitignore`]),ue=g();let N=0;function P(e,n,i,a={}){let o=Date.now();N+=1;let s=N,c=a.filePaths?`${a.filePaths.length} 个指定文件`:`全工程`;return s>1&&e.debug(`[crawl] 排队:入队时队列长度 ${s}(${c})`),ue(async()=>{--N;let l=Date.now()-o;l>=250?e.info(`[crawl] 等串行锁 ${l}ms 才拿到(入队时队列 ${s},${c}) —— 用户视角就是「点了没反应」`):e.debug(`[crawl] 拿到串行锁,等待 ${l}ms(${c})`),e.debug(`开始扫描组件,扫描参数: ${JSON.stringify(a)}`);let d=Date.now(),f=t.join(O(n.rootDir,n.frameworkPluginName,n.frameworkPluginVersion??`unknown`),`components.json`),p=await(async()=>{if(a.filePaths)return a.filePaths.map(e=>t.join(n.rootDir,e));e.debug(`扫描目录: ${n.rootDir},采集可扫描文件`);let r=await k(n.rootDir,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,{ignoredPaths:i.ignoredPaths});return e.debug(`找到 ${r.length} 个包含组件的文件`),r})(),m=new Set(p.map(e=>t.relative(n.rootDir,e).replace(/\\/g,`/`))),h={detectionStartTimestamp:0,components:[],stories:[]};if(u.existsSync(f))try{h=JSON.parse(u.readFileSync(f,`utf8`))}catch{e.warn(`无法转换 ${f} 中存储的缓存信息`)}h.detectionStartTimestamp<await fe(n.rootDir)&&(h={detectionStartTimestamp:0,components:[],stories:[]});let g=p.filter(e=>{let t=n.reader.readSync(e);return t?.kind===`file`&&(a.forceRefresh||t.lastModifiedMillis()>=h.detectionStartTimestamp)}),_=new Set(g.map(e=>t.relative(n.rootDir,e).replace(/\\/g,`/`))),v=({id:e})=>{let t=r(e).filePath;return m.has(t)&&!_.has(t)};e.debug(`[crawl] 缓存${u.existsSync(f)?`存在`:`缺失(冷启动)`},重扫 ${g.length}/${p.length} 个文件`);let y=h.components.filter(v),b=h.stories.filter(v),{components:x,stories:S}=await de(e,n,i,g),C=[...y,...x],w=[...b,...S];if(!a.filePaths){await u.mkdirp(t.dirname(f));let e={detectionStartTimestamp:d,components:C,stories:w};await u.writeFile(f,JSON.stringify(e))}return e.debug(`[crawl] 完成,用时 ${Date.now()-d}ms(${c},组件 ${C.length},story ${w.length})`),{components:C,stories:w}})}async function de(e,n,r,i){let a=[],o=[];if(i.length===0)return{components:a,stories:o};e.debug(`在下述文件中查找组件:\n- ${i.map(e=>t.relative(n.rootDir,e)).join(`
2
+ - `)}`);let s=await r.crawlFiles(i);e.debug(`组件检测完成`);for(let e of s.components)a.push({id:e.id,sourcePosition:e.sourcePosition,exported:e.exported});for(let e of s.stories)o.push({id:e.id,sourcePosition:e.sourcePosition,associatedComponentId:e.associatedComponent?.id||null});return{components:a,stories:o}}async function fe(e){let n=t.join(e,`node_modules`),r=0;if(await u.pathExists(n))for(let e of await u.readdir(n)){let i=t.join(n,e),a=await u.lstat(i);(a.isDirectory()||a.isSymbolicLink())&&(r=Math.max(r,a.mtimeMs))}for(let n of M){let i=t.join(e,n);if(await u.pathExists(i)){let e=await u.stat(i);r=Math.max(r,e.mtimeMs)}}return r}async function pe(e){for(let t=e;;t++)if(await me(t))return t}async function me(e){return new Promise(t=>{let n=v.createServer();n.unref(),n.on(`error`,()=>t(!1)),n.listen(e,()=>{n.close(()=>{t(!0)})})})}const he=e(import.meta.url);async function F(e,n){let r=t.join(n,`package.json`);if(!await u.pathExists(r))return{};let{dependencies:i,devDependencies:a,peerDependencies:o}=JSON.parse(await u.readFile(r,`utf8`)),s={...i,...a,...o},c=new Map;for(let[r,i]of Object.entries(s)){let a=0;typeof i==`string`&&(a=i.startsWith(`^`)||i.startsWith(`~`)?Number.parseInt(i.slice(1)):Number.parseInt(i)),c.set(r,{majorVersion:a,readInstalledVersion:async()=>{try{let e=ge(r,n),i=e;for(;i!==t.dirname(i);){let e=t.join(i,`package.json`);if(u.existsSync(e)){let t=JSON.parse(await u.readFile(e,`utf8`));if(typeof t.version==`string`)return t.version;throw Error(`包: ${e} 的版本号异常`)}i=t.dirname(i)}throw Error(`根据模块: ${e} 的入口路径无法找到 package.json`)}catch(t){return e.error(t,`无法读取包: ${r} 的安装版本, 你可能没有正确安装项目的依赖,请重新安装。`),null}}})}return Object.fromEntries(c)}function ge(e,t){try{return he.resolve(e,{paths:[t]})}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ERR_PACKAGE_PATH_NOT_EXPORTED`){let t=e.message.match(/No "exports" main defined in (.*)(\/|\\)package\.json/);if(t)return t[1]??``}throw e}}const I=`/__static`;function _e(e){return async(t,n)=>{let r=await ye(typeof t.query.path==`string`?t.query.path:null,e);if(r.ok===!1){n.status(r.status).type(`text/plain; charset=utf-8`).end(r.message);return}let i;try{i=await f.promises.stat(r.absolutePath)}catch{n.status(404).type(`text/plain; charset=utf-8`).end(`文件不存在`);return}if(!i.isFile()){n.status(404).type(`text/plain; charset=utf-8`).end(`不是文件`);return}n.status(200).type(be(r.absolutePath)),f.createReadStream(r.absolutePath).on(`error`,()=>{n.destroy()}).pipe(n)}}function L(e,n){let r=t.relative(e,n);return r===``?!0:!r.startsWith(`..`)&&!t.isAbsolute(r)}function ve(e,n){if(!t.isAbsolute(e))return{ok:!1};let r=t.resolve(e);for(let e of n)if(L(t.resolve(e),r))return{ok:!0,absolutePath:r};return{ok:!1}}async function ye(e,n,r=x){if(typeof e!=`string`||e.trim()===``)return{ok:!1,status:400,message:`缺少 path 参数`};if(n.length===0)return{ok:!1,status:403,message:`没有可访问的静态目录`};let i=ve(e,n);if(!i.ok)return{ok:!1,status:403,message:`该路径不在允许的静态目录内`};let a;try{a=await r(i.absolutePath)}catch{return{ok:!1,status:404,message:`文件不存在`}}return(await Promise.all(n.map(async e=>{try{return await r(t.resolve(e))}catch{return t.resolve(e)}}))).some(e=>L(e,a))?{ok:!0,absolutePath:a}:{ok:!1,status:403,message:`该路径不在允许的静态目录内`}}function be(e){switch(t.extname(e).toLowerCase()){case`.html`:case`.htm`:return`text/html; charset=utf-8`;case`.css`:return`text/css; charset=utf-8`;case`.js`:case`.mjs`:return`text/javascript; charset=utf-8`;case`.json`:return`application/json; charset=utf-8`;case`.svg`:return`image/svg+xml`;case`.png`:return`image/png`;case`.jpg`:case`.jpeg`:return`image/jpeg`;case`.gif`:return`image/gif`;case`.webp`:return`image/webp`;case`.ico`:return`image/x-icon`;case`.woff`:return`font/woff`;case`.woff2`:return`font/woff2`;case`.txt`:return`text/plain; charset=utf-8`;default:return`application/octet-stream`}}const R=[`preview.config.js`,`preview.config.mjs`,`preview.config.ts`,`preview.config.cjs`,`preview.config.mts`,`preview.config.cts`];async function xe(e,n){let r={};for(let i of R){let a=t.join(e,i);if(f.existsSync(a))try{let t=await ee({command:`serve`,mode:`development`},i,e,n);if(t){r=t.config;break}}catch(e){throw e instanceof Error&&typeof e.message==`string`&&e.message.includes(`config 必须导出或者返回一个对象`)?Error(`请使用一个 preview.config.js 的默认导出`):e}}return r}function z(e){let t=e;return t.startsWith(`Error: Build failed with 1 error:
3
3
  `)&&(t=t.substring(e.indexOf(`
4
4
  `)+1)),t.startsWith(`Error:`)&&(t=t.substring(t.indexOf(`:`)+1)),t=t.trim(),`<html>
5
5
  <head>
@@ -31,8 +31,8 @@ import{createRequire as e}from"node:module";import t from"node:path";import{crea
31
31
  });
32
32
  <\/script>
33
33
  </head>
34
- <body>${ie(e)}</body>
35
- </html>`}const we=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]),Te=/import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;function Ee(){return{name:`previewjs:css-modules-without-suffix`,async transform(e,n){let r=n.split(`?`)[0];return!r||!we.has(t.extname(r))?null:e.replace(Te,`import $1 from "$3.$4?$5&.module.css"`)}}}const L=`__fakeValueExport__`;let R=null;function De(){return R??=import(`typescript`).then(e=>e.default??e),R}function Oe(e){let t=new Map;return{name:`cfp:fake-type-exports`,async transform(n,r){if(!r.endsWith(`.ts`)&&!r.endsWith(`.tsx`)||r.endsWith(`.d.ts`))return;let i=await e.readFile(r);if(i===null||!i.includes(`export`))return;let a=t.get(r);if((a===void 0||a.text!==i)&&(a={text:i,names:await ke(r,i)},t.set(r,a)),a.names.length!==0)return`${n}\nconst ${L} = null;\nexport { ${a.names.map(e=>`${L} as ${e}`).join(`, `)} };`}}}async function ke(e,t){let n=await De(),r=e.endsWith(`.tsx`);return Ae(n,n.createSourceFile(e,t,n.ScriptTarget.Latest,!1,r?n.ScriptKind.TSX:n.ScriptKind.TS))}function Ae(e,t){let n=new Set,r=new Set,i=new Map,a=(e,{asType:t,asValue:n})=>{let r=i.get(e)??{asType:!1,asValue:!1};r.asType=r.asType||t===!0,r.asValue=r.asValue||n===!0,i.set(e,r)};for(let i of t.statements){let t=je(e,i);if(e.isTypeAliasDeclaration(i)||e.isInterfaceDeclaration(i)){let e=i.name.text;n.add(e),t&&a(e,{asType:!0});continue}if(e.isClassDeclaration(i)||e.isEnumDeclaration(i)){if(!i.name)continue;let e=i.name.text;n.add(e),r.add(e),t&&a(e,{asType:!0,asValue:!0});continue}if(e.isFunctionDeclaration(i)){if(!i.name)continue;let e=i.name.text;r.add(e),t&&a(e,{asValue:!0});continue}if(e.isVariableStatement(i)){for(let n of i.declarationList.declarations){if(!e.isIdentifier(n.name))continue;let i=n.name.text;r.add(i),t&&a(i,{asValue:!0})}continue}if(e.isExportDeclaration(i)&&i.exportClause&&!i.moduleSpecifier&&e.isNamedExports(i.exportClause))for(let e of i.exportClause.elements){let t=(e.propertyName??e.name).text;a(t,{asType:!0,asValue:!i.isTypeOnly})}}let o=[];for(let[e,t]of i)n.has(e)&&(t.asValue&&r.has(e)||o.push(e));return o}function je(e,t){let n=t.modifiers;return n!==void 0&&n.some(t=>t.kind===e.SyntaxKind.ExportKeyword)}function Me(){return{name:`previewjs:invalidate-stories-modules-on-update`,enforce:`post`,transform:e=>e.includes(`import.meta.hot.accept(`)?`${e}
34
+ <body>${re(e)}</body>
35
+ </html>`}const Se=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]),Ce=/import\s+([\S]+)\s+from\s+('|")([\S]+)\.(css|less|sass|scss|styl|stylus|postcss)(\?[\S]*)?&?('|")/g;function we(){return{name:`previewjs:css-modules-without-suffix`,async transform(e,n){let r=n.split(`?`)[0];return!r||!Se.has(t.extname(r))?null:e.replace(Ce,`import $1 from "$3.$4?$5&.module.css"`)}}}const B=`__fakeValueExport__`;let V=null;function Te(){return V??=import(`typescript`).then(e=>e.default??e),V}function Ee(e){let t=new Map;return{name:`cfp:fake-type-exports`,async transform(n,r){if(!r.endsWith(`.ts`)&&!r.endsWith(`.tsx`)||r.endsWith(`.d.ts`))return;let i=await e.readFile(r);if(i===null||!i.includes(`export`))return;let a=t.get(r);if((a===void 0||a.text!==i)&&(a={text:i,names:await De(r,i)},t.set(r,a)),a.names.length!==0)return`${n}\nconst ${B} = null;\nexport { ${a.names.map(e=>`${B} as ${e}`).join(`, `)} };`}}}async function De(e,t){let n=await Te(),r=e.endsWith(`.tsx`);return Oe(n,n.createSourceFile(e,t,n.ScriptTarget.Latest,!1,r?n.ScriptKind.TSX:n.ScriptKind.TS))}function Oe(e,t){let n=new Set,r=new Set,i=new Map,a=(e,{asType:t,asValue:n})=>{let r=i.get(e)??{asType:!1,asValue:!1};r.asType=r.asType||t===!0,r.asValue=r.asValue||n===!0,i.set(e,r)};for(let i of t.statements){let t=ke(e,i);if(e.isTypeAliasDeclaration(i)||e.isInterfaceDeclaration(i)){let e=i.name.text;n.add(e),t&&a(e,{asType:!0});continue}if(e.isClassDeclaration(i)||e.isEnumDeclaration(i)){if(!i.name)continue;let e=i.name.text;n.add(e),r.add(e),t&&a(e,{asType:!0,asValue:!0});continue}if(e.isFunctionDeclaration(i)){if(!i.name)continue;let e=i.name.text;r.add(e),t&&a(e,{asValue:!0});continue}if(e.isVariableStatement(i)){for(let n of i.declarationList.declarations){if(!e.isIdentifier(n.name))continue;let i=n.name.text;r.add(i),t&&a(i,{asValue:!0})}continue}if(e.isExportDeclaration(i)&&i.exportClause&&!i.moduleSpecifier&&e.isNamedExports(i.exportClause))for(let e of i.exportClause.elements){let t=(e.propertyName??e.name).text;a(t,{asType:!0,asValue:!i.isTypeOnly})}}let o=[];for(let[e,t]of i)n.has(e)&&(t.asValue&&r.has(e)||o.push(e));return o}function ke(e,t){let n=t.modifiers;return n!==void 0&&n.some(t=>t.kind===e.SyntaxKind.ExportKeyword)}function Ae(){return{name:`previewjs:invalidate-stories-modules-on-update`,enforce:`post`,transform:e=>e.includes(`import.meta.hot.accept(`)?`${e}
36
36
  if (import.meta?.hot) {
37
37
  import.meta.hot.accept(newModule => {
38
38
  if (newModule?.default?.component) {
@@ -40,11 +40,11 @@ import{createRequire as e}from"node:module";import t from"node:path";import{crea
40
40
  }
41
41
  });
42
42
  }
43
- `:null}}function Ne(){return{name:`previewjs:local-eval`,enforce:`post`,transform:(e,t)=>t.indexOf(`/node_modules/`)!==-1||t.indexOf(`?`)!==-1?null:`${e}
43
+ `:null}}function je(){return{name:`previewjs:local-eval`,enforce:`post`,transform:(e,t)=>t.indexOf(`/node_modules/`)!==-1||t.indexOf(`?`)!==-1?null:`${e}
44
44
  export const PreviewJsEval = (code, args = {}) => {
45
45
  return eval("(({ " + Object.keys(args).join(", ") + "}) => { " + code + " })(args)");
46
46
  }
47
- `}}function Pe(){return{name:`previewjs:preview-script`,load(e){if(!e.startsWith(`/__previewjs_internal__/preview.js?p=`))return null;let t=e.substring(37);return Fe(JSON.parse(Buffer.from(t,`base64url`).toString(`utf8`)))}}}function Fe({previewablePath:e,previewableName:t,wrapperPath:n,wrapperName:r,detectedGlobalCssFilePaths:i}){return`
47
+ `}}function Me(){return{name:`previewjs:preview-script`,load(e){if(!e.startsWith(`/__previewjs_internal__/preview.js?p=`))return null;let t=e.substring(37);return Ne(JSON.parse(Buffer.from(t,`base64url`).toString(`utf8`)))}}}function Ne({previewablePath:e,previewableName:t,wrapperPath:n,wrapperName:r,detectedGlobalCssFilePaths:i}){return`
48
48
  // 导入初始化监听器和预览的函数
49
49
  import { initListeners, initPreview } from "/__previewjs_internal__/index.ts";
50
50
  // 初始化监听器
@@ -123,4 +123,4 @@ import{createRequire as e}from"node:module";import t from"node:path";import{crea
123
123
  function loadFreshWrapperModule() {
124
124
  return import(/* @vite-ignore */ "/${n}?t=" + Date.now());
125
125
  }
126
- `}function Ie({rootDir:e,publicDir:n}){return{name:`previewjs:public-asset-import`,resolveId:async(r,i)=>{if(!i||!r.startsWith(`/`)||r.startsWith(`/__previewjs__/`))return null;let a=t.join(e,n),o=t.join(a,r);return!o.startsWith(a+t.sep)||!await u.pathExists(o)?null:r}}}function z(e){let t=e;return t.match(/^[a-z]:/)&&(t=t[0]?.toUpperCase()+e.substring(1)),t.replace(/\\/g,`/`)}const B=`/@cfp-studio-virtual:`,V=`/@id/__x00__`,H=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]);function U(e){let t=e;return t.startsWith(B)&&(t=t.slice(21)),t.startsWith(`\0`)&&(t=t.slice(1)),t.startsWith(V)&&(t=t.slice(12)),[t,t!==e]}function Le(e){let{reader:n,rootDir:r}=e;return{name:`previewjs:virtual-fs`,resolveId:async(e,n)=>{let[r,a]=n?U(n):[null,!1];if(e.indexOf(`/node_modules/`)!==-1)return null;let[o]=U(e);o=o.split(`?`,2)[0]??``;let s=t.extname(o),c;if(t.isAbsolute(o))c=o;else{if(!r)return null;if(s&&!H.has(s)&&s!==`.svg`)return t.join(t.dirname(r),o);c=t.join(t.dirname(r),o)}let l=await i(c);if(l){let[e]=l;return await u.pathExists(e)&&!a?null:(c.endsWith(s)||(c+=s),B+e.replace(/\\/g,`/`))}return null},load:async n=>{let a=n;if(a.indexOf(`/node_modules/`)!==-1)return null;a.startsWith(B)&&(a=a.slice(21)),a.startsWith(`\0`)&&(a=a.slice(1)),a.startsWith(V)&&(a=a.slice(12));let o=await i(a);if(!o)return null;let[s,c]=o,l=!1;for(let n of e.allowedAbsolutePaths){let e=t.relative(n,s);if(e&&!e.startsWith(`..`)&&!t.isAbsolute(e)){l=!0;break}}if(!l)return e.logger.error(`试图访问的 ${s} 文件在运行访问的目录之外. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(c.kind!==`file`)return e.logger.error(`无法读取文件:${s}`),null;let u=await c.read(),d=t.extname(s);if(!H.has(d))return u;let f=t.extname(n);return{code:!n.includes(`__previewjs_internal__`)&&(f===``||f===`.js`)?(await re(u,s,{loader:s.endsWith(`.ts`)?`ts`:`tsx`,format:`esm`,target:`es2020`,sourcefile:t.relative(r,s),...e.esbuildOptions})).code:u}},transform:(e,t)=>t.startsWith(B)?{code:e,map:{mappings:``,names:[],sources:[],version:3}}:null,handleHotUpdate:async i=>{let a=e.moduleGraph();if(!a)return null;let o=t.relative(r,i.file),s=t.join(r,o),c=await n.read(s);if(!c||c.kind!==`file`)return null;let l=B+z(s),u=a.getModuleById(l);return u&&[u]}};async function i(e){return await a(e)||await a(t.join(r,e))}async function a(e){for(let r of[``,...H,...[...H].map(e=>`${t.sep}index${e}`)]){let t=`${e}${r}`,i=await n.read(t);if(i?.kind===`file`)return[t,i]}return null}}function Re(e,t){let n=e.environments?Object.values(e.environments):[];if(n.length>0)for(let e of n)e.moduleGraph.onFileChange(t);else e.moduleGraph.onFileChange(t);for(let n of e.watcher.listeners(`change`))try{n(t)}catch{}}function ze(e={platform:process.platform},t){return t&&typeof t.usePolling==`boolean`||e.platform!==`win32`?t:{...t,usePolling:!0,interval:t?.interval??300}}const W=e(import.meta.url);function G(e){let n=K(e);if(!n)return e;let r=Be(e),i=t.dirname(t.dirname(n)),a=r?t.join(i,`src`,`${r}.ts`):t.join(i,`src`,`index.ts`);return u.existsSync(a)?a:n}function Be(e){let t=e.split(`/`),n=e.startsWith(`@`)?2:1;return t.length===n+1?t[n]:void 0}function Ve(e){let n=K(e);return n?t.dirname(t.dirname(n)):void 0}function He(e){for(let n of q()){let r=n.endsWith(`.mjs`)||n.endsWith(`.js`)?t.dirname(n):n,i=t.join(r,`node_modules`,...e.split(`/`));if(u.existsSync(i))return i}}function K(e){for(let n of q()){let r=h(n.endsWith(t.sep)?n:`${n}${t.sep}`).href;try{return m(import.meta.resolve(e,r))}catch{}try{return W.resolve(e,{paths:[n]})}catch{}}}function q(){let e=[We];try{e.push(t.dirname(W.resolve(`@cfp-studio/iframe/package.json`)))}catch{}return e}const J=[`@cfp-studio/fiber-reader`,`@cfp-studio/analyzer-api/error-panel`,`@cfp-studio/analyzer-api/empty-hint`];function Ue(){let e=[];for(let t of J){let n=Ve(t)??He(t);n&&e.push(n)}return[...new Set(e)]}const We=t.dirname(m(import.meta.url)),Ge=[`.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`],Y=[`index`,`global`,`globals`,`style`,`styles`,`app`],X=[`css`,`sass`,`scss`,`less`,`styl`,`stylus`],Ke=Y.flatMap(e=>X.map(t=>`${e}.${t}`)),qe=new Set([...F,...A,...Ge,...Ke,`vite.config.js`,`vite.config.ts`,`svelte.config.js`]);async function Z(e){return e?.kind===`starting`?e.promise:e}var Je=class{#e=null;#t;#n={onChange:(e,n)=>{this.onFileChanged(t.resolve(e),n).catch(e=>this.options.logger.error(e))}};get state(){return this.#e}constructor(e){this.options=e;let t=l.Router();t.use(async(e,t,n)=>{let r=await Z(this.#e);if(!r||r.kind===`error`)return n();try{r.viteServer.middlewares(e,t,n)}catch(e){this.options.logger.error(`Vite middleware error: ${e}`),t.status(500).end(`Vite middleware error: ${e}`)}}),this.middleware=t,this.#t=g()}async loadIndexHtml(e,n){return this.#t(async()=>{try{let i=await Z(this.#e);if(!i)return I(`Vite server is not running`);if(i.kind===`error`)return I(i.error);let a=await u.readFile(this.options.shadowHtmlFilePath,`utf-8`),{config:o,viteServer:s}=i,{filePath:c,name:l}=r(n),d=c.replace(/\\/g,`/`),f=o.wrapper,p=f&&await u.pathExists(t.join(this.options.rootDir,f.path))?f.path.replace(/\\/g,`/`):null;return await s.transformIndexHtml(e,a.replace(`<!-- %OPTIONAL_HEAD_CONTENT% -->`,`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(JSON.stringify({previewablePath:d,previewableName:l,wrapperPath:p,wrapperName:f?.componentName||null,detectedGlobalCssFilePaths:o.detectedGlobalCssFilePaths}),`utf8`).toString(`base64url`)}"><\/script>`))}catch(e){return I(`${e}`)}})}async start(){let e;this.#e={kind:`starting`,promise:new Promise(t=>{e=e=>{this.#e=e,t(e)}})},this.options.reader.listeners.add(this.#n);try{process.chdir(this.options.rootDir);let n=await Ce(this.options.rootDir,Xe(this.options.logger)),r=await O(this.options.rootDir,`**/@(${Y.join(`|`)}).@(${X.join(`|`)})`,{maxDepth:3}),i={...n,wrapper:n.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:r.map(e=>t.relative(this.options.rootDir,e))},a=[],o=null;for(let e of[`tsconfig.json`,`jsconfig.json`]){let n=t.join(this.options.rootDir,e);try{if(await u.pathExists(n)){let e=ee(n)||null;if(e){o=Qe.parse(e);break}}}catch(e){this.options.logger.warn(`Unable to load tsconfig from ${n}: ${e}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(o||null,null,2)}`);let s=o?.compilerOptions?.baseUrl||``,c=o?.compilerOptions?.paths||{},l=s.startsWith(`./`)?s.substring(1):s;l&&!l.endsWith(`/`)&&(l+=`/`);for(let[e,n]of Object.entries(c)){let r=n[0];if(!r)continue;let i=e.endsWith(`/*`)?e.slice(0,e.length-2):e,o=r.endsWith(`/*`)?r.slice(0,r.length-2):r;a.push({find:i,replacement:t.join(this.options.rootDir,s,o)})}let d=await C.loadConfigFromFile({command:`serve`,mode:`development`},void 0,this.options.rootDir),f=C.createLogger(Xe(this.options.logger)),p=this.options.frameworkPlugin.viteConfig(await $([...d?.config.plugins||[],...i.vite?.plugins||[]])),m=i.vite?.publicDir||d?.config.publicDir||p.publicDir||i.publicDir||`public`,h=Ze(this.options.reader,await $([S({root:this.options.rootDir}),Pe(),Le({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:[...i.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[ne(this.options.rootDir)],...Ue()],moduleGraph:()=>this.#e?.kind===`running`?this.#e.viteServer.moduleGraph:null,esbuildOptions:p.esbuild||{}}),Ne(),Me(),Oe({readFile:e=>this.options.reader.read(e).then(e=>e?.kind===`file`?e.read():null)}),Ee(),Ie({rootDir:this.options.rootDir,publicDir:m}),p.plugins]));this.options.logger.debug(`Creating Vite server`);let g=await C.createServer({...p,...d?.config,...i.vite,optimizeDeps:$e(p.optimizeDeps,d?.config.optimizeDeps,i.vite?.optimizeDeps),configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,watch:ze(void 0,i.vite?.server?.watch),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:(e,t)=>f.info(`[vite] ${e}`,t),warn:(e,t)=>f.warn(`[vite] ${e}`,t),error:(e,t)=>{e.startsWith(`\x1B[31mInternal server error`)||this.#e?.kind===`running`&&this.#e.viteServer.ws.send({type:`error`,err:{message:e,stack:``}}),f.error(`[vite] ${e}`,t)},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:h,define:{__filename:void 0,__dirname:void 0,process:void 0,...p.define,...d?.config.define,...i.vite?.define},resolve:{...d?.config.resolve,...i.vite?.resolve,alias:[{find:`@cfp-studio/fiber-reader`,replacement:G(`@cfp-studio/fiber-reader`)},...J.filter(e=>e!==`@cfp-studio/fiber-reader`).map(e=>({find:RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`),replacement:G(e)})),...Q(i.vite?.resolve?.alias),...Q(i.alias),...Q(d?.config.resolve?.alias),...a,...Q(p.resolve?.alias),...Ye(l)?[{find:/^~(.*)/,replacement:`${l}$1`},{find:`@`,replacement:l}]:[]]}});e({kind:`running`,config:i,viteServer:g}),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 this.#e.promise}async stop({restart:e}={restart:!1}){await this.#t(async()=>{this.options.reader.listeners.remove(this.#n);let t=await Z(this.#e);return t?.kind===`running`&&await t.viteServer.close(),e?this.start():this.#e=null})}async onFileChanged(e,n){let r=await Z(this.state);if(!r)return;if(!n.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(t.relative(this.options.rootDir,e)),qe.has(t.basename(e)))){this.options.logger.info(`检测到依赖变化. 重启服务...`),await this.stop({restart:!0});return}if(r.kind!==`running`)return;let{viteServer:i,config:a}=r;n.virtual?Re(i,z(e)):a.wrapper&&e===t.resolve(this.options.rootDir,a.wrapper.path)&&(i.moduleGraph.invalidateAll(),i.ws.send({type:`full-reload`}))}};function Q(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({find:e,replacement:t})):[]}function Ye(e){return e!==``&&e!==`./`&&e!==`.`}async function $(e){let t=[];for(let n of await Promise.all(e))n&&(Array.isArray(n)?t.push(...await $(n)):t.push(n));return t}function Xe(e){switch(e.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 e.warn(`Unknown log level: ${e.level}`),`info`}}function Ze(e,t){return t.map(async t=>{if(!t.handleHotUpdate)return t;let n=typeof t.handleHotUpdate==`function`?t.handleHotUpdate:t.handleHotUpdate.handler;return{...t,handleHotUpdate:async t=>{await n({...t,read:async()=>{let n=await e.read(t.file);return n?.kind===`file`?n.read():t.read()}})}}})}const Qe=w.object({compilerOptions:w.object({baseUrl:w.string().optional(),paths:w.record(w.array(w.string())).optional()}).optional()});function $e(...e){let t=e.filter(e=>!!e);if(t.length===0)return;let n={};for(let e of t)Object.assign(n,e);let r=t.flatMap(e=>e.exclude??[]);r.length>0&&(n.exclude=[...new Set(r)]);let i=t.flatMap(e=>e.include??[]);i.length>0&&(n.include=[...new Set(i)]);let a=t.map(e=>e.esbuildOptions).filter(Boolean);if(a.length>0){let e={};for(let t of a)Object.assign(e,t);let t=a.flatMap(e=>e?.plugins??[]);t.length>0&&(e.plugins=t),n.esbuildOptions=e}return n}var et=class{constructor(e){this.options=e,this.viteManager=null,this.status={kind:`stopped`},this.disposeObserver=null,this.transformingReader=s([e.reader,o({mapping:{from:e.frameworkPlugin.previewDirPath,to:t.join(e.rootDir,`__previewjs_internal__`,`renderer`)},watch:!1}),o({mapping:{from:e.previewDirPath,to:e.rootDir},watch:!1})])}async start(){let e=this.status;switch(e.kind){case`starting`:try{await e.promise}catch(e){this.options.logger.error(e),this.status={kind:`stopped`},await this.startFromStopped()}break;case`started`:break;case`stopping`:try{await e.promise}catch(e){this.options.logger.error(e),this.status={kind:`stopped`}}await this.start();break;case`stopped`:await this.startFromStopped();break;default:throw y(e)}}async startFromStopped(){this.status={kind:`starting`,promise:(async()=>{let e=l.Router();if(e.use((e,t,n)=>{t.setHeader(`Cache-Control`,`max-age=0, must-revalidate`),n()}),e.use(this.options.middlewares),e.get([N,`${N}/*splat`],ye([this.options.rootDir,...this.options.staticRoots??[]])),e.get(/^\/.*:[^/]+\/$/,async(e,t,n)=>{let r=e.header(`Accept`);if(e.url.includes(`?html-proxy`)){n();return}if(r===`text/x-vite-ping`){t.writeHead(204).end();return}let i=e.path.substring(1,e.path.length-1);if(!this.viteManager){t.status(404).end(`Vite服务器未启动`);return}t.status(200).set({"Content-Type":`text/html`}).end(await this.viteManager.loadIndexHtml(e.originalUrl,i))}),e.use(`/ping`,async(e,t)=>{t.json(JSON.stringify({pong:`match!`}))}),e.use((e,t,n)=>{this.viteManager?.middleware(e,t,n)}),this.transformingReader.observe)try{this.disposeObserver=await this.transformingReader.observe(this.options.rootDir)}catch(e){this.options.logger.error(e,`启动文件系统监听失败:`)}let{server:n,disposeHttpServer:r}=await this.options.getHttpServer(e);se(this.options.rootDir)&&this.options.logger.debug(`已清理旧缓存目录 node_modules/.previewjs`),this.options.logger.debug(`启动 Vite manager ...`),this.viteManager=new Je({rootDir:this.options.rootDir,shadowHtmlFilePath:t.join(this.options.previewDirPath,`index.html`),reader:this.transformingReader,cacheDir:t.join(E(this.options.rootDir),`vite`),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:n,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug(`预览服务已就绪`),this.status={kind:`started`,onStop:r}})()},await this.status.promise;for(let e=0;;e++)try{await b.get(`http://localhost:${this.options.port}`);break}catch(t){if(e===10)throw t;await new Promise(e=>setTimeout(e,50))}}async stop(){if(this.status.kind===`starting`)try{await this.status.promise}catch{this.status={kind:`stopped`}}if(this.status.kind!==`started`)return;let 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}},tt=class{constructor(e){this.logger=e,this.handlers=new Map,this.registerRPC=(e,t)=>{if(this.handlers.has(e.path))throw Error(`端点 '${e.path}' 已经注册了 handler,是否重复注册?`);this.handlers.set(e.path,t)}}async handle(e,t){let n=this.handlers.get(e);if(!n)return{kind:`error`,message:`路径 '${e}' 没有注册对应的 handler`};this.logger.debug(`RPC ${e} invoked`);try{return{kind:`success`,response:await n(t)}}catch(t){return this.logger.error(`RPC ${e} failed: ${t}`),t instanceof Error?{kind:`error`,message:t.message}:{kind:`error`,message:`${t}`}}}};async function nt(e,t,n){let r=await M(e,t);for(let e of n)if(e.info&&await e.isCompatible(r,t))return e.info?.name;return null}async function rt(e,t,n){let r=await M(e,t),i=[];for(let e of n){if(!e.info)continue;let n=e.info.name;try{i.push({name:n,compatible:await e.isCompatible(r,t),error:null})}catch(e){i.push({name:n,compatible:!1,error:String(e)})}}return i}const it=e(import.meta.url);process.on(`uncaughtException`,e=>{console.error(`Core 遇到未捕获的异常`,e)}),process.on(`unhandledRejection`,e=>{console.error(`Core 遇到未处理的 Promise 对象`,e)});async function at({rootDir:e,frameworkPlugin:s,logger:u=n(void 0,`core`),reader:f=o(),onServerStart:p=()=>Promise.resolve({}),staticRoots:m=[]}){if(!s.info)throw Error(`framework plugin 与当前版本 ${T()} 不兼容. 请升级.`);if(s.info.apiVersion>5)throw Error(` ${s.info.name} 的 API 版本是 ${s.info.apiVersion}. 高于当前安装的 ${T()}, 请升级至最新版本.`);let h=await M(u,e);if(!await s.isCompatible(h,e))throw Error(` ${s.info.name} 与当前工作区的前端框架版本不兼容。`);u.info(`使用 ${s.info.name} 在目录: ${e} 中创建工作区`);let g=await s.create({rootDir:e,reader:f,logger:u,dependencies:h}),_=new Set,v={frameworkPluginName:s.info.name,frameworkPluginVersion:s.info.version,crawlFiles:g.crawlFiles,crawlProject:e=>j(u,v,g,e??{}),findGitignoredSourceFiles:()=>ue(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,g.ignoredPaths),inspectScanCache:async()=>{let t=await O(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,{ignoredPaths:g.ignoredPaths});return ce(e,s.info.name,s.info.version??`unknown`,t)},clearScanCache:()=>le(e,s.info.name,s.info.version??`unknown`),typeAnalyzer:g.typeAnalyzer,rootDir:e,reader:f,startServer:async({asMiddleware:n,port:o,clientPort:h,onStop:y}={})=>{let b=o||await he(3140),x=new tt(u);x.registerRPC(i.Analyze,async({previewableIds:n})=>{u.debug(`分析: ${n.join(`, `)}`);let i=await g.crawlFiles([...new Set(n.map(n=>t.join(e,r(n).filePath)))]);u.debug(`检测到 ${i.components.length} 个组件和 ${i.stories.length} 个story`);let o=[],s=Object.fromEntries(i.components.map(e=>[e.id,e])),c=Object.fromEntries(i.stories.map(e=>[e.id,e])),l={};for(let e of n){let t=s[e],n=c[e],i;if(t){let n;u.debug(`分析组件: ${e}`),{props:n,types:i}=await t.analyze(),o.push({kind:`component`,id:e,exported:t.exported,sourcePosition:t.sourcePosition,props:n})}else if(n){let t;n.associatedComponent?({props:t,types:i}=await n.associatedComponent.analyze(),u.debug(`分析 story: ${e} 的关联组件`)):(u.debug(`story: ${e} 没有关联的组件`),t=a,i={});let r=null;({args:r}=await n.analyze()),o.push({kind:`story`,id:e,sourcePosition:n.sourcePosition,associatedComponentId:n.associatedComponent?.id||null,props:t,args:r}),u.debug(`story args: ${JSON.stringify(r)}`)}else{let{filePath:t,name:n}=r(e);throw Error(`在 ${t} 中未找到组件 ${n}. `)}l={...l,...i}}return{previewables:o,types:l}}),x.registerRPC(i.GetInfo,async()=>({frameworkPlugin:s.info})),x.registerRPC(i.CrawlFiles,e=>j(u,v,g,e));let S=[c(),l.json(),async(e,t,n)=>{e.path.startsWith(`/api/`)?t.json(await x.handle(e.path.substr(5),e.body)):n()}];if(p){let{middlewares:e=[]}=await p({registerRPC:(e,t)=>x.registerRPC(e,t),workspace:v});S.push(...e)}let ee=n?async e=>{let t=n.register(e);return{server:n.server,disposeHttpServer:async()=>{t()}}}:async e=>{u.debug(`启动 Express 服务器`);let t=l();t.use(e);let n=await new Promise(e=>{let n=t.listen(b,()=>{u.info(`${T()} 预览服务运行在 http://localhost:${b}.`),e(n)})}),r=d({server:n,gracefulTerminationTimeout:0});return{server:n,disposeHttpServer:async()=>{await r.terminate(),u.info(`${T()} 预览服务器已停止.`)}}},C=new et({reader:f,rootDir:e,previewDirPath:t.join(t.dirname(t.dirname(it.resolve(`@cfp-studio/iframe`))),`preview`),frameworkPlugin:g,logger:u,middlewares:S,getHttpServer:ee,port:b,clientPort:h,staticRoots:m});return await C.start(),_.add(C),{port:b,stop:async()=>{_.delete(C),await C.stop(),await y?.()}}},dispose:async()=>{await Promise.all([..._].map(e=>e.stop())),_.clear(),g.dispose()}};return v}function ot(e){let n=t.resolve(e);for(;n!==t.dirname(n);){if(u.existsSync(t.join(n,`package.json`)))return n;n=t.dirname(n)}return null}export{at as createWorkspace,M as extractPackageDependencies,nt as findCompatiblePlugin,ot as findWorkspaceRoot,rt as probeFrameworkCompatibility,z as toVitePath};
126
+ `}function Pe({rootDir:e,publicDir:n}){return{name:`previewjs:public-asset-import`,resolveId:async(r,i)=>{if(!i||!r.startsWith(`/`)||r.startsWith(`/__previewjs__/`))return null;let a=t.join(e,n),o=t.join(a,r);return!o.startsWith(a+t.sep)||!await u.pathExists(o)?null:r}}}function H(e){let t=e;return t.match(/^[a-z]:/)&&(t=t[0]?.toUpperCase()+e.substring(1)),t.replace(/\\/g,`/`)}const U=`/@cfp-studio-virtual:`,W=`/@id/__x00__`,G=new Set([`.js`,`.jsx`,`.ts`,`.tsx`]);function K(e){let t=e;return t.startsWith(U)&&(t=t.slice(21)),t.startsWith(`\0`)&&(t=t.slice(1)),t.startsWith(W)&&(t=t.slice(12)),[t,t!==e]}function Fe(e){let{reader:n,rootDir:r}=e;return{name:`previewjs:virtual-fs`,resolveId:async(e,n)=>{let[r,a]=n?K(n):[null,!1];if(e.indexOf(`/node_modules/`)!==-1)return null;let[o]=K(e);o=o.split(`?`,2)[0]??``;let s=t.extname(o),c;if(t.isAbsolute(o))c=o;else{if(!r)return null;if(s&&!G.has(s)&&s!==`.svg`)return t.join(t.dirname(r),o);c=t.join(t.dirname(r),o)}let l=await i(c);if(l){let[e]=l;return await u.pathExists(e)&&!a?null:(c.endsWith(s)||(c+=s),U+e.replace(/\\/g,`/`))}return null},load:async n=>{let a=n;if(a.indexOf(`/node_modules/`)!==-1)return null;a.startsWith(U)&&(a=a.slice(21)),a.startsWith(`\0`)&&(a=a.slice(1)),a.startsWith(W)&&(a=a.slice(12));let o=await i(a);if(!o)return null;let[s,c]=o,l=!1;for(let n of e.allowedAbsolutePaths){let e=t.relative(n,s);if(e&&!e.startsWith(`..`)&&!t.isAbsolute(e)){l=!0;break}}if(!l)return e.logger.error(`试图访问的 ${s} 文件在运行访问的目录之外. See https://vitejs.dev/config/server-options.html#server-fs-allow for more information.`),null;if(c.kind!==`file`)return e.logger.error(`无法读取文件:${s}`),null;let u=await c.read(),d=t.extname(s);if(!G.has(d))return u;let f=t.extname(n);return{code:!n.includes(`__previewjs_internal__`)&&(f===``||f===`.js`)?(await ne(u,s,{loader:s.endsWith(`.ts`)?`ts`:`tsx`,format:`esm`,target:`es2020`,sourcefile:t.relative(r,s),...e.esbuildOptions})).code:u}},transform:(e,t)=>t.startsWith(U)?{code:e,map:{mappings:``,names:[],sources:[],version:3}}:null,handleHotUpdate:async i=>{let a=e.moduleGraph();if(!a)return null;let o=t.relative(r,i.file),s=t.join(r,o),c=await n.read(s);if(!c||c.kind!==`file`)return null;let l=U+H(s),u=a.getModuleById(l);return u&&[u]}};async function i(e){return await a(e)||await a(t.join(r,e))}async function a(e){for(let r of[``,...G,...[...G].map(e=>`${t.sep}index${e}`)]){let t=`${e}${r}`,i=await n.read(t);if(i?.kind===`file`)return[t,i]}return null}}function Ie(e,t){let n=e.environments?Object.values(e.environments):[];if(n.length>0)for(let e of n)e.moduleGraph.onFileChange(t);else e.moduleGraph.onFileChange(t);for(let n of e.watcher.listeners(`change`))try{n(t)}catch{}}function Le(e={platform:process.platform},t){return t&&typeof t.usePolling==`boolean`||e.platform!==`win32`?t:{...t,usePolling:!0,interval:t?.interval??300}}const q=e(import.meta.url);function J(e){let n=Y(e);if(!n)return e;let r=Re(e),i=t.dirname(t.dirname(n)),a=r?t.join(i,`src`,`${r}.ts`):t.join(i,`src`,`index.ts`);return u.existsSync(a)?a:n}function Re(e){let t=e.split(`/`),n=e.startsWith(`@`)?2:1;return t.length===n+1?t[n]:void 0}function ze(e){let n=Y(e);return n?t.dirname(t.dirname(n)):void 0}function Be(e){for(let n of Ve()){let r=n.endsWith(`.mjs`)||n.endsWith(`.js`)?t.dirname(n):n,i=t.join(r,`node_modules`,...e.split(`/`));if(u.existsSync(i))return i}}function Y(e){for(let n of Ve()){let r=h(n.endsWith(t.sep)?n:`${n}${t.sep}`).href;try{return m(import.meta.resolve(e,r))}catch{}try{return q.resolve(e,{paths:[n]})}catch{}}}function Ve(){let e=[We];try{e.push(t.dirname(q.resolve(`@cfp-studio/iframe/package.json`)))}catch{}return e}const He=[`@cfp-studio/fiber-reader`,`@cfp-studio/analyzer-api/error-panel`,`@cfp-studio/analyzer-api/empty-hint`];function Ue(){let e=[];for(let t of He){let n=ze(t)??Be(t);n&&e.push(n)}return[...new Set(e)]}const We=t.dirname(m(import.meta.url)),Ge=[`.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`],Ke=[`index`,`global`,`globals`,`style`,`styles`,`app`],qe=[`css`,`sass`,`scss`,`less`,`styl`,`stylus`],Je=Ke.flatMap(e=>qe.map(t=>`${e}.${t}`)),Ye=new Set([...R,...M,...Ge,...Je,`vite.config.js`,`vite.config.ts`,`svelte.config.js`]);async function X(e){return e?.kind===`starting`?e.promise:e}var Xe=class{#e=null;#t;#n={onChange:(e,n)=>{this.onFileChanged(t.resolve(e),n).catch(e=>this.options.logger.error(e))}};get state(){return this.#e}constructor(e){this.options=e;let t=l.Router();t.use(async(e,t,n)=>{let r=await X(this.#e);if(!r||r.kind===`error`)return n();try{r.viteServer.middlewares(e,t,n)}catch(e){this.options.logger.error(`Vite middleware error: ${e}`),t.status(500).end(`Vite middleware error: ${e}`)}}),this.middleware=t,this.#t=g()}async loadIndexHtml(e,n){return this.#t(async()=>{try{let i=await X(this.#e);if(!i)return z(`Vite server is not running`);if(i.kind===`error`)return z(i.error);let a=await u.readFile(this.options.shadowHtmlFilePath,`utf-8`),{config:o,viteServer:s}=i,{filePath:c,name:l}=r(n),d=c.replace(/\\/g,`/`),f=o.wrapper,p=f&&await u.pathExists(t.join(this.options.rootDir,f.path))?f.path.replace(/\\/g,`/`):null;return await s.transformIndexHtml(e,a.replace(`<!-- %OPTIONAL_HEAD_CONTENT% -->`,`<script type="module" src="/__previewjs_internal__/preview.js?p=${Buffer.from(JSON.stringify({previewablePath:d,previewableName:l,wrapperPath:p,wrapperName:f?.componentName||null,detectedGlobalCssFilePaths:o.detectedGlobalCssFilePaths}),`utf8`).toString(`base64url`)}"><\/script>`))}catch(e){return z(`${e}`)}})}async start(){let e;this.#e={kind:`starting`,promise:new Promise(t=>{e=e=>{this.#e=e,t(e)}})},this.options.reader.listeners.add(this.#n);try{process.chdir(this.options.rootDir);let n=await xe(this.options.rootDir,$(this.options.logger)),r=await k(this.options.rootDir,`**/@(${Ke.join(`|`)}).@(${qe.join(`|`)})`,{maxDepth:3}),i={...n,wrapper:n.wrapper||{path:this.options.frameworkPlugin.defaultWrapperPath},detectedGlobalCssFilePaths:r.map(e=>t.relative(this.options.rootDir,e))},a=[],o=null;for(let e of[`tsconfig.json`,`jsconfig.json`]){let n=t.join(this.options.rootDir,e);try{if(await u.pathExists(n)){let e=C(n)||null;if(e){o=$e.parse(e);break}}}catch(e){this.options.logger.warn(`Unable to load tsconfig from ${n}: ${e}`)}}this.options.logger.debug(`Loaded ts/jsconfig: ${JSON.stringify(o||null,null,2)}`);let s=o?.compilerOptions?.baseUrl||``,c=o?.compilerOptions?.paths||{},l=s.startsWith(`./`)?s.substring(1):s;l&&!l.endsWith(`/`)&&(l+=`/`);for(let[e,n]of Object.entries(c)){let r=n[0];if(!r)continue;let i=e.endsWith(`/*`)?e.slice(0,e.length-2):e,o=r.endsWith(`/*`)?r.slice(0,r.length-2):r;a.push({find:i,replacement:t.join(this.options.rootDir,s,o)})}let d=await w.loadConfigFromFile({command:`serve`,mode:`development`},void 0,this.options.rootDir),f=w.createLogger($(this.options.logger)),p=this.options.frameworkPlugin.viteConfig(await Q([...d?.config.plugins||[],...i.vite?.plugins||[]])),m=i.vite?.publicDir||d?.config.publicDir||p.publicDir||i.publicDir||`public`,h=Qe(this.options.reader,await Q([S({root:this.options.rootDir}),Me(),Fe({logger:this.options.logger,reader:this.options.reader,rootDir:this.options.rootDir,allowedAbsolutePaths:[...i.vite?.server?.fs?.allow||d?.config.server?.fs?.allow||[te(this.options.rootDir)],...Ue()],moduleGraph:()=>this.#e?.kind===`running`?this.#e.viteServer.moduleGraph:null,esbuildOptions:p.esbuild||{}}),je(),Ae(),Ee({readFile:e=>this.options.reader.read(e).then(e=>e?.kind===`file`?e.read():null)}),we(),Pe({rootDir:this.options.rootDir,publicDir:m}),p.plugins]));this.options.logger.debug(`Creating Vite server`);let g=await w.createServer({...p,...d?.config,...i.vite,optimizeDeps:et(p.optimizeDeps,d?.config.optimizeDeps,i.vite?.optimizeDeps),configFile:!1,root:this.options.rootDir,server:{middlewareMode:!0,watch:Le(void 0,i.vite?.server?.watch),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:(e,t)=>f.info(`[vite] ${e}`,t),warn:(e,t)=>f.warn(`[vite] ${e}`,t),error:(e,t)=>{e.startsWith(`\x1B[31mInternal server error`)||this.#e?.kind===`running`&&this.#e.viteServer.ws.send({type:`error`,err:{message:e,stack:``}}),f.error(`[vite] ${e}`,t)},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:h,define:{__filename:void 0,__dirname:void 0,process:void 0,...p.define,...d?.config.define,...i.vite?.define},resolve:{...d?.config.resolve,...i.vite?.resolve,alias:[{find:`@cfp-studio/fiber-reader`,replacement:J(`@cfp-studio/fiber-reader`)},...He.filter(e=>e!==`@cfp-studio/fiber-reader`).map(e=>({find:RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`),replacement:J(e)})),...Z(i.vite?.resolve?.alias),...Z(i.alias),...Z(d?.config.resolve?.alias),...a,...Z(p.resolve?.alias),...Ze(l)?[{find:/^~(.*)/,replacement:`${l}$1`},{find:`@`,replacement:l}]:[]]}});e({kind:`running`,config:i,viteServer:g}),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 this.#e.promise}async stop({restart:e}={restart:!1}){await this.#t(async()=>{this.options.reader.listeners.remove(this.#n);let t=await X(this.#e);return t?.kind===`running`&&await t.viteServer.close(),e?this.start():this.#e=null})}async onFileChanged(e,n){let r=await X(this.state);if(!r)return;if(!n.virtual&&(this.options.frameworkPlugin.typeAnalyzer.invalidateCachedTypesForFile(t.relative(this.options.rootDir,e)),Ye.has(t.basename(e)))){this.options.logger.info(`检测到依赖变化. 重启服务...`),await this.stop({restart:!0});return}if(r.kind!==`running`)return;let{viteServer:i,config:a}=r;n.virtual?Ie(i,H(e)):a.wrapper&&e===t.resolve(this.options.rootDir,a.wrapper.path)&&(i.moduleGraph.invalidateAll(),i.ws.send({type:`full-reload`}))}};function Z(e){return e?Array.isArray(e)?e:Object.entries(e).map(([e,t])=>({find:e,replacement:t})):[]}function Ze(e){return e!==``&&e!==`./`&&e!==`.`}async function Q(e){let t=[];for(let n of await Promise.all(e))n&&(Array.isArray(n)?t.push(...await Q(n)):t.push(n));return t}function $(e){switch(e.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 e.warn(`Unknown log level: ${e.level}`),`info`}}function Qe(e,t){return t.map(async t=>{if(!t.handleHotUpdate)return t;let n=typeof t.handleHotUpdate==`function`?t.handleHotUpdate:t.handleHotUpdate.handler;return{...t,handleHotUpdate:async t=>{await n({...t,read:async()=>{let n=await e.read(t.file);return n?.kind===`file`?n.read():t.read()}})}}})}const $e=T.object({compilerOptions:T.object({baseUrl:T.string().optional(),paths:T.record(T.array(T.string())).optional()}).optional()});function et(...e){let t=e.filter(e=>!!e);if(t.length===0)return;let n={};for(let e of t)Object.assign(n,e);let r=t.flatMap(e=>e.exclude??[]);r.length>0&&(n.exclude=[...new Set(r)]);let i=t.flatMap(e=>e.include??[]);i.length>0&&(n.include=[...new Set(i)]);let a=t.map(e=>e.esbuildOptions).filter(Boolean);if(a.length>0){let e={};for(let t of a)Object.assign(e,t);let t=a.flatMap(e=>e?.plugins??[]);t.length>0&&(e.plugins=t),n.esbuildOptions=e}return n}var tt=class{constructor(e){this.options=e,this.viteManager=null,this.status={kind:`stopped`},this.disposeObserver=null,this.transformingReader=s([e.reader,o({mapping:{from:e.frameworkPlugin.previewDirPath,to:t.join(e.rootDir,`__previewjs_internal__`,`renderer`)},watch:!1}),o({mapping:{from:e.previewDirPath,to:e.rootDir},watch:!1})])}async start(){let e=this.status;switch(e.kind){case`starting`:try{await e.promise}catch(e){this.options.logger.error(e),this.status={kind:`stopped`},await this.startFromStopped()}break;case`started`:break;case`stopping`:try{await e.promise}catch(e){this.options.logger.error(e),this.status={kind:`stopped`}}await this.start();break;case`stopped`:await this.startFromStopped();break;default:throw y(e)}}async startFromStopped(){this.status={kind:`starting`,promise:(async()=>{let e=l.Router();if(e.use((e,t,n)=>{t.setHeader(`Cache-Control`,`max-age=0, must-revalidate`),n()}),e.use(this.options.middlewares),e.get([I,`${I}/*splat`],_e([this.options.rootDir,...this.options.staticRoots??[]])),e.get(/^\/.*:[^/]+\/$/,async(e,t,n)=>{let r=e.header(`Accept`);if(e.url.includes(`?html-proxy`)){n();return}if(r===`text/x-vite-ping`){t.writeHead(204).end();return}let i=e.path.substring(1,e.path.length-1);if(!this.viteManager){t.status(404).end(`Vite服务器未启动`);return}t.status(200).set({"Content-Type":`text/html`}).end(await this.viteManager.loadIndexHtml(e.originalUrl,i))}),e.use(`/ping`,async(e,t)=>{t.json(JSON.stringify({pong:`match!`}))}),e.use((e,t,n)=>{this.viteManager?.middleware(e,t,n)}),this.transformingReader.observe)try{this.disposeObserver=await this.transformingReader.observe(this.options.rootDir)}catch(e){this.options.logger.error(e,`启动文件系统监听失败:`)}let{server:n,disposeHttpServer:r}=await this.options.getHttpServer(e);oe(this.options.rootDir)&&this.options.logger.debug(`已清理旧缓存目录 node_modules/.previewjs`),this.options.logger.debug(`启动 Vite manager ...`),this.viteManager=new Xe({rootDir:this.options.rootDir,shadowHtmlFilePath:t.join(this.options.previewDirPath,`index.html`),reader:this.transformingReader,cacheDir:t.join(D(this.options.rootDir),`vite`),logger:this.options.logger,frameworkPlugin:this.options.frameworkPlugin,server:n,port:this.options.port,clientPort:this.options.clientPort}),this.viteManager.start(),this.options.logger.debug(`预览服务已就绪`),this.status={kind:`started`,onStop:r}})()},await this.status.promise;for(let e=0;;e++)try{await b.get(`http://localhost:${this.options.port}`);break}catch(t){if(e===10)throw t;await new Promise(e=>setTimeout(e,50))}}async stop(){if(this.status.kind===`starting`)try{await this.status.promise}catch{this.status={kind:`stopped`}}if(this.status.kind!==`started`)return;let 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}},nt=class{constructor(e){this.logger=e,this.handlers=new Map,this.registerRPC=(e,t)=>{if(this.handlers.has(e.path))throw Error(`端点 '${e.path}' 已经注册了 handler,是否重复注册?`);this.handlers.set(e.path,t)}}async handle(e,t){let n=this.handlers.get(e);if(!n)return{kind:`error`,message:`路径 '${e}' 没有注册对应的 handler`};this.logger.debug(`RPC ${e} invoked`);try{return{kind:`success`,response:await n(t)}}catch(t){return this.logger.error(`RPC ${e} failed: ${t}`),t instanceof Error?{kind:`error`,message:t.message}:{kind:`error`,message:`${t}`}}}};async function rt(e,t,n){let r=await F(e,t);for(let e of n)if(e.info&&await e.isCompatible(r,t))return e.info?.name;return null}async function it(e,t,n){let r=await F(e,t),i=[];for(let e of n){if(!e.info)continue;let n=e.info.name;try{i.push({name:n,compatible:await e.isCompatible(r,t),error:null})}catch(e){i.push({name:n,compatible:!1,error:String(e)})}}return i}const at=e(import.meta.url);process.on(`uncaughtException`,e=>{console.error(`Core 遇到未捕获的异常`,e)}),process.on(`unhandledRejection`,e=>{console.error(`Core 遇到未处理的 Promise 对象`,e)});async function ot({rootDir:e,frameworkPlugin:s,logger:u=n(void 0,`core`),reader:f=o(),onServerStart:p=()=>Promise.resolve({}),staticRoots:m=[]}){if(!s.info)throw Error(`framework plugin 与当前版本 ${E()} 不兼容. 请升级.`);if(s.info.apiVersion>5)throw Error(` ${s.info.name} 的 API 版本是 ${s.info.apiVersion}. 高于当前安装的 ${E()}, 请升级至最新版本.`);let h=await F(u,e);if(!await s.isCompatible(h,e))throw Error(` ${s.info.name} 与当前工作区的前端框架版本不兼容。`);u.info(`使用 ${s.info.name} 在目录: ${e} 中创建工作区`);let g=await s.create({rootDir:e,reader:f,logger:u,dependencies:h}),_=new Set,v={frameworkPluginName:s.info.name,frameworkPluginVersion:s.info.version,crawlFiles:g.crawlFiles,crawlProject:e=>P(u,v,g,e??{}),findGitignoredSourceFiles:()=>le(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,g.ignoredPaths),inspectScanCache:async()=>{let t=await k(e,`**/*.@(js|jsx|ts|tsx|svelte|vue)`,{ignoredPaths:g.ignoredPaths});return se(e,s.info.name,s.info.version??`unknown`,t)},clearScanCache:()=>ce(e,s.info.name,s.info.version??`unknown`),typeAnalyzer:g.typeAnalyzer,rootDir:e,reader:f,startServer:async({asMiddleware:n,port:o,clientPort:h,onStop:y}={})=>{let b=o||await pe(3140),x=new nt(u);x.registerRPC(i.Analyze,async({previewableIds:n})=>{u.debug(`分析: ${n.join(`, `)}`);let i=await g.crawlFiles([...new Set(n.map(n=>t.join(e,r(n).filePath)))]);u.debug(`检测到 ${i.components.length} 个组件和 ${i.stories.length} 个story`);let o=[],s=Object.fromEntries(i.components.map(e=>[e.id,e])),c=Object.fromEntries(i.stories.map(e=>[e.id,e])),l={};for(let e of n){let t=s[e],n=c[e],i;if(t){let n;u.debug(`分析组件: ${e}`),{props:n,types:i}=await t.analyze(),o.push({kind:`component`,id:e,exported:t.exported,sourcePosition:t.sourcePosition,props:n})}else if(n){let t;n.associatedComponent?({props:t,types:i}=await n.associatedComponent.analyze(),u.debug(`分析 story: ${e} 的关联组件`)):(u.debug(`story: ${e} 没有关联的组件`),t=a,i={});let r=null;({args:r}=await n.analyze()),o.push({kind:`story`,id:e,sourcePosition:n.sourcePosition,associatedComponentId:n.associatedComponent?.id||null,props:t,args:r}),u.debug(`story args: ${JSON.stringify(r)}`)}else{let{filePath:t,name:n}=r(e);throw Error(`在 ${t} 中未找到组件 ${n}. `)}l={...l,...i}}return{previewables:o,types:l}}),x.registerRPC(i.GetInfo,async()=>({frameworkPlugin:s.info})),x.registerRPC(i.CrawlFiles,e=>P(u,v,g,e));let S=[c(),l.json(),async(e,t,n)=>{e.path.startsWith(`/api/`)?t.json(await x.handle(e.path.substr(5),e.body)):n()}];if(p){let{middlewares:e=[]}=await p({registerRPC:(e,t)=>x.registerRPC(e,t),workspace:v});S.push(...e)}let C=n?async e=>{let t=n.register(e);return{server:n.server,disposeHttpServer:async()=>{t()}}}:async e=>{u.debug(`启动 Express 服务器`);let t=l();t.use(e);let n=await new Promise(e=>{let n=t.listen(b,()=>{u.info(`${E()} 预览服务运行在 http://localhost:${b}.`),e(n)})}),r=d({server:n,gracefulTerminationTimeout:0});return{server:n,disposeHttpServer:async()=>{await r.terminate(),u.info(`${E()} 预览服务器已停止.`)}}},w=new tt({reader:f,rootDir:e,previewDirPath:t.join(t.dirname(t.dirname(at.resolve(`@cfp-studio/iframe`))),`preview`),frameworkPlugin:g,logger:u,middlewares:S,getHttpServer:C,port:b,clientPort:h,staticRoots:m});return await w.start(),_.add(w),{port:b,stop:async()=>{_.delete(w),await w.stop(),await y?.()}}},dispose:async()=>{await Promise.all([..._].map(e=>e.stop())),_.clear(),g.dispose()}};return v}function st(e){let n=t.resolve(e);for(;n!==t.dirname(n);){if(u.existsSync(t.join(n,`package.json`)))return n;n=t.dirname(n)}return null}export{ot as createWorkspace,F as extractPackageDependencies,rt as findCompatiblePlugin,st as findWorkspaceRoot,it as probeFrameworkCompatibility,H as toVitePath};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cfp-studio/core",
3
- "version": "1.0.15",
3
+ "version": "1.0.16",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist"
@@ -25,12 +25,12 @@
25
25
  "typescript": "5.9.3",
26
26
  "vite": "6.4.5",
27
27
  "zod": "3.24.1",
28
+ "@cfp-studio/api": "16.1.2",
28
29
  "@cfp-studio/analyzer-api": "0.1.17",
30
+ "@cfp-studio/type-analyzer": "10.1.9",
29
31
  "@cfp-studio/fiber-reader": "0.3.0",
30
- "@cfp-studio/api": "16.1.2",
31
32
  "@cfp-studio/vfs": "2.1.8",
32
- "@cfp-studio/type-analyzer": "10.1.9",
33
- "@cfp-studio/iframe": "18.4.9"
33
+ "@cfp-studio/iframe": "18.4.11"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@rollup/plugin-alias": "5.1.1",