@amaster.ai/vite-plugins 1.0.0-beta.44 → 1.0.0-beta.46

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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var g=require('fs'),d=require('path'),x=require('process'),m=require('fs/promises'),R=require('esbuild'),buffer=require('buffer');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var g__default=/*#__PURE__*/_interopDefault(g);var d__default=/*#__PURE__*/_interopDefault(d);var x__default=/*#__PURE__*/_interopDefault(x);var m__default=/*#__PURE__*/_interopDefault(m);var R__namespace=/*#__PURE__*/_interopNamespace(R);var A=`<script>
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var g=require('fs'),d=require('path'),x=require('process'),m=require('fs/promises'),O=require('esbuild'),buffer=require('buffer');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var g__default=/*#__PURE__*/_interopDefault(g);var d__default=/*#__PURE__*/_interopDefault(d);var x__default=/*#__PURE__*/_interopDefault(x);var m__default=/*#__PURE__*/_interopDefault(m);var O__namespace=/*#__PURE__*/_interopNamespace(O);var A=`<script>
2
2
  document.addEventListener("click", (e) => {
3
3
  const element = e.target;
4
4
  const noJumpOut = document.body.classList.contains("forbid-jump-out")
@@ -16,10 +16,10 @@ document.addEventListener("click", (e) => {
16
16
  e.preventDefault();
17
17
  }
18
18
  });
19
- </script>`;function I(r,o){return `<script type="module">
19
+ </script>`;function I(r){return `<script type="module">
20
20
  (function() {
21
21
  const SOURCE_KEY = Symbol.for("__jsxSource__");
22
- const SESSION_KEY = "${o}";
22
+ const SESSION_KEY = "${r}";
23
23
 
24
24
  // Expose minimal API for external bridge script
25
25
  window.__AMASTER_BRIDGE__ = {
@@ -28,7 +28,7 @@ document.addEventListener("click", (e) => {
28
28
  postToParent: (type, data) => {
29
29
  window.parent.postMessage({ type, data, key: SESSION_KEY }, "*");
30
30
  },
31
- isDev: ${r},
31
+ isDev: true,
32
32
  };
33
33
 
34
34
  // Listen for bridge script URL from platform
@@ -40,15 +40,22 @@ document.addEventListener("click", (e) => {
40
40
  return;
41
41
  }
42
42
 
43
- if (type === "amaster.loadBridge" && data?.scriptUrl) {
43
+ if (type === "amaster.loadBridge" && data?.scriptContent) {
44
+ console.log("[Bridge] Loading bridge from inline script");
45
+
46
+ // Create blob URL from script content
47
+ const blob = new Blob([data.scriptContent], { type: 'application/javascript' });
48
+ const blobUrl = URL.createObjectURL(blob);
49
+
44
50
  const script = document.createElement("script");
45
- script.src = data.scriptUrl;
51
+ script.src = blobUrl;
46
52
  script.onload = () => {
47
53
  console.log("[Bridge] External script loaded");
48
- window.__AMASTER_BRIDGE__?.postToParent("amaster.bridge.ready", {});
54
+ URL.revokeObjectURL(blobUrl);
49
55
  };
50
56
  script.onerror = () => {
51
57
  console.error("[Bridge] Failed to load external script");
58
+ URL.revokeObjectURL(blobUrl);
52
59
  };
53
60
  document.head.appendChild(script);
54
61
  }
@@ -58,13 +65,13 @@ document.addEventListener("click", (e) => {
58
65
  window.__AMASTER_BRIDGE__?.postToParent("amaster.bridge.initialized", {});
59
66
  });
60
67
  })();
61
- </script>`}function b(){let r=false;return {name:"vite-plugin-editor-bridge",configResolved(o){r=o.command==="serve";},transformIndexHtml(o){if(!r)return o;let t=process.env.VITE_AMASTER_KEY||"",e=I(r,t),n=`${A}${e}</body>`;return o.replace("</body>",n)}}}function E(r){let o=false,t=r?.routesFilePath||"src/routes.tsx";return {name:"vite-plugin-routes-expose",enforce:"post",configResolved(e){o=e.command==="serve";},transform(e,n){if(!o||!n.endsWith(t))return null;try{return e.includes("window.__APP_ROUTES__")?null:{code:`${e}
68
+ </script>`}function _(){let r=false;return {name:"vite-plugin-editor-bridge",configResolved(o){r=o.command==="serve";},transformIndexHtml(o){if(!r)return o;console.log("[editorBridgePlugin] Injecting bridge script");let t=process.env.VITE_AMASTER_KEY||"",e=I(t),n=`${A}${e}</body>`;return o.replace("</body>",n)}}}function E(r){let o=false,t=r?.routesFilePath||"src/routes.tsx";return {name:"vite-plugin-routes-expose",enforce:"post",configResolved(e){o=e.command==="serve";},transform(e,n){if(!o||!n.endsWith(t))return null;try{return e.includes("window.__APP_ROUTES__")?null:{code:`${e}
62
69
 
63
70
  // Development mode: Expose routes to window.__APP_ROUTES__
64
71
  if (typeof window !== 'undefined') {
65
72
  window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];
66
73
  }
67
- `,map:null}}catch{return null}}}}function O(){let r="",o=`
74
+ `,map:null}}catch{return null}}}}function R(){let r="",o=`
68
75
  <script>
69
76
  (function() {
70
77
  'use strict';
@@ -892,7 +899,7 @@ export function jsxDEV(type, props, key, isStatic, source, self) {
892
899
 
893
900
  return _jsxDEV(type, props, key, isStatic, source, self);
894
901
  }
895
- `;function v(){let r=false,o="";return {name:"vite-plugin-jsx-source-tagger",enforce:"pre",configResolved(t){r=t.command==="serve",o=t.root;},resolveId(t,e){return r&&t==="react/jsx-dev-runtime"&&!e?.includes("\0jsx-source")?"\0jsx-source/jsx-dev-runtime":null},load(t){return r&&t==="\0jsx-source/jsx-dev-runtime"?C.replace('const PROJECT_ROOT = "";',`const PROJECT_ROOT = ${JSON.stringify(o)};`):null}}}function _(r){let o="",t=false,e=null,n=r?.configPath||"./tailwind.config.ts",a="@amaster/tailwind-config",s="\0"+a,l=async()=>{let i=d__default.default.resolve(o,n);try{return await m__default.default.access(i),i}catch{if(n.endsWith(".ts")){let u=i.replace(/\.ts$/,".js");try{return await m__default.default.access(u),u}catch{return null}}else if(n.endsWith(".js")){let u=i.replace(/\.js$/,".ts");try{return await m__default.default.access(u),u}catch{return null}}return null}},c=async()=>{try{let i=await l();if(!i)return null;let u=await m__default.default.readFile(i,"utf-8"),p=await R__namespace.transform(u,{loader:i.endsWith(".ts")?"ts":"js",format:"esm",platform:"node"}),h=await import(`data:text/javascript;base64,${buffer.Buffer.from(p.code).toString("base64")}`);if(!h?.default)throw new Error("Invalid Tailwind config structure");try{let P=(await import('tailwindcss/resolveConfig.js')).default;e=P(h.default);}catch{e=h.default;}return e}catch{return null}};return {name:"vite-plugin-tailwind-config-sync",configResolved(i){o=i.root,t=i.command==="serve";},async buildStart(){t&&await c();},resolveId(i){if(i===a)return s},async load(i){if(i===s)return e||await c(),`
902
+ `;function v(){let r=false,o="";return {name:"vite-plugin-jsx-source-tagger",enforce:"pre",configResolved(t){r=t.command==="serve",o=t.root;},resolveId(t,e){return r&&t==="react/jsx-dev-runtime"&&!e?.includes("\0jsx-source")?"\0jsx-source/jsx-dev-runtime":null},load(t){return r&&t==="\0jsx-source/jsx-dev-runtime"?C.replace('const PROJECT_ROOT = "";',`const PROJECT_ROOT = ${JSON.stringify(o)};`):null}}}function w(r){let o="",t=false,e=null,n=r?.configPath||"./tailwind.config.ts",a="@amaster/tailwind-config",s="\0"+a,l=async()=>{let i=d__default.default.resolve(o,n);try{return await m__default.default.access(i),i}catch{if(n.endsWith(".ts")){let u=i.replace(/\.ts$/,".js");try{return await m__default.default.access(u),u}catch{return null}}else if(n.endsWith(".js")){let u=i.replace(/\.js$/,".ts");try{return await m__default.default.access(u),u}catch{return null}}return null}},c=async()=>{try{let i=await l();if(!i)return null;let u=await m__default.default.readFile(i,"utf-8"),p=await O__namespace.transform(u,{loader:i.endsWith(".ts")?"ts":"js",format:"esm",platform:"node"}),h=await import(`data:text/javascript;base64,${buffer.Buffer.from(p.code).toString("base64")}`);if(!h?.default)throw new Error("Invalid Tailwind config structure");try{let P=(await import('tailwindcss/resolveConfig.js')).default;e=P(h.default);}catch{e=h.default;}return e}catch{return null}};return {name:"vite-plugin-tailwind-config-sync",configResolved(i){o=i.root,t=i.command==="serve";},async buildStart(){t&&await c();},resolveId(i){if(i===a)return s},async load(i){if(i===s)return e||await c(),`
896
903
  let config = ${JSON.stringify(e)};
897
904
 
898
905
  let _updateConfig;
@@ -914,7 +921,7 @@ export default new Proxy(config, {
914
921
  return target[prop];
915
922
  }
916
923
  });
917
- `},configureServer(i){t&&(async()=>{try{let u=await l();u&&i.watcher.add(u);}catch{}})();},async handleHotUpdate({file:i,server:u}){let p=await l();if(!p||d__default.default.normalize(i)!==d__default.default.normalize(p))return;await c();let f=u.moduleGraph.getModuleById(s);return f?(u.moduleGraph.invalidateModule(f),[f]):[]}}}function w(r={}){let{designWidth:o=375,maxWidth:t=750,baseFontSize:e=12,minRootSize:n=12,maxRootSize:a=24}=r;return {name:"vite-plugin-taro-style-adapter",apply:"serve",transformIndexHtml(s){let l=`
924
+ `},configureServer(i){t&&(async()=>{try{let u=await l();u&&i.watcher.add(u);}catch{}})();},async handleHotUpdate({file:i,server:u}){let p=await l();if(!p||d__default.default.normalize(i)!==d__default.default.normalize(p))return;await c();let f=u.moduleGraph.getModuleById(s);return f?(u.moduleGraph.invalidateModule(f),[f]):[]}}}function b(r={}){let{designWidth:o=375,maxWidth:t=750,baseFontSize:e=12,minRootSize:n=12,maxRootSize:a=24}=r;return {name:"vite-plugin-taro-style-adapter",apply:"serve",transformIndexHtml(s){let l=`
918
925
  <script data-taro-flexible="true">
919
926
  (function() {
920
927
  var designWidth = ${o};
@@ -1001,5 +1008,5 @@ export default new Proxy(config, {
1001
1008
  object-fit: contain;
1002
1009
  }
1003
1010
  </style>
1004
- </head>`)}}}function y(r={}){let{ratio:o=2}=r;return {postcssPlugin:"postcss-rpx2px",Declaration(t){t.value.includes("rpx")&&(t.value=t.value.replace(/(-?\d*\.?\d+)rpx/gi,(e,n)=>{let a=parseFloat(n)/o;return a===0?"0":`${a}px`}));}}}y.postcss=true;function k(r={}){let{additional:o=[],autoInjectTaroApp:t=true,autoInjectVite:e=true}=r,n={},a=new Set(o);return t&&Object.keys(process.env).forEach(s=>{s.startsWith("TARO_APP_")&&a.add(s);}),e&&Object.keys(process.env).forEach(s=>{s.startsWith("VITE_")&&a.add(s);}),a.forEach(s=>{let l=process.env[s]||"";n[`process.env.${s}`]=JSON.stringify(l);}),n}function L(){return {"process.env.TARO_APP_API_BASE_URL":JSON.stringify(process.env.TARO_APP_API_BASE_URL||""),"process.env.VITE_API_BASE_URL":JSON.stringify(process.env.VITE_API_BASE_URL||"")}}function q(r={}){let o=r.isTaro??x__default.default.env.TARO_ENV==="h5",t=[b(),E()];return r.jsxSourceTagger!==false&&t.push(v()),r.tailwindConfigSync!==false&&t.push(_({configPath:r.tailwindConfigPath})),o&&(t.unshift(w(r.styleAdapter)),t.unshift({name:"dev-postcss-rpx2px-plugin",apply:"serve",config(e){typeof e.css?.postcss=="object"&&e.css?.postcss.plugins?.unshift(y());}})),x__default.default.env.WORKSPACE_GIT_REPO&&t.push(O()),t}exports.default=q;exports.editorBridgePlugin=b;exports.injectAmasterEnv=L;exports.injectTaroEnv=k;exports.jsxSourceTaggerPlugin=v;exports.routesExposePlugin=E;exports.rpx2pxPlugin=y;exports.tailwindConfigSyncPlugin=_;exports.taroStyleAdapterPlugin=w;//# sourceMappingURL=index.cjs.map
1011
+ </head>`)}}}function y(r={}){let{ratio:o=2}=r;return {postcssPlugin:"postcss-rpx2px",Declaration(t){t.value.includes("rpx")&&(t.value=t.value.replace(/(-?\d*\.?\d+)rpx/gi,(e,n)=>{let a=parseFloat(n)/o;return a===0?"0":`${a}px`}));}}}y.postcss=true;function k(r={}){let{additional:o=[],autoInjectTaroApp:t=true,autoInjectVite:e=true}=r,n={},a=new Set(o);return t&&Object.keys(process.env).forEach(s=>{s.startsWith("TARO_APP_")&&a.add(s);}),e&&Object.keys(process.env).forEach(s=>{s.startsWith("VITE_")&&a.add(s);}),a.forEach(s=>{let l=process.env[s]||"";n[`process.env.${s}`]=JSON.stringify(l);}),n}function L(){return {"process.env.TARO_APP_API_BASE_URL":JSON.stringify(process.env.TARO_APP_API_BASE_URL||""),"process.env.VITE_API_BASE_URL":JSON.stringify(process.env.VITE_API_BASE_URL||"")}}function q(r={}){let o=r.isTaro??x__default.default.env.TARO_ENV==="h5",t=[_(),E()];return r.jsxSourceTagger!==false&&t.push(v()),r.tailwindConfigSync!==false&&t.push(w({configPath:r.tailwindConfigPath})),o&&(t.unshift(b(r.styleAdapter)),t.unshift({name:"dev-postcss-rpx2px-plugin",apply:"serve",config(e){typeof e.css?.postcss=="object"&&e.css?.postcss.plugins?.unshift(y());}})),x__default.default.env.WORKSPACE_GIT_REPO&&t.push(R()),t}exports.default=q;exports.editorBridgePlugin=_;exports.injectAmasterEnv=L;exports.injectTaroEnv=k;exports.jsxSourceTaggerPlugin=v;exports.routesExposePlugin=E;exports.rpx2pxPlugin=y;exports.tailwindConfigSyncPlugin=w;exports.taroStyleAdapterPlugin=b;//# sourceMappingURL=index.cjs.map
1005
1012
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/editor-bridge.ts","../src/routes-expose.ts","../src/browser-logs.ts","../src/tagger.ts","../src/tailwind-config-sync.ts","../src/taro-style-adapter.ts","../src/postcss-rpx2px.ts","../src/taro-env-inject.ts","../src/index.ts"],"names":["clickHandlerScript","getBridgeScriptContent","isDev","sessionKey","editorBridgePlugin","config","html","bridgeScript","scriptsToInject","routesExposePlugin","options","routesPath","code","id","browserLogsPlugin","logFilePath","injectedScript","workspaceDir","process","path","dir","fs","devServer","req","res","next","origin","body","chunk","logDir","error","devRuntimeCode","jsxSourceTaggerPlugin","projectRoot","importer","tailwindConfigSyncPlugin","cachedConfig","configPath","VIRTUAL_MODULE_ID","RESOLVED_VIRTUAL_MODULE_ID","findConfigFile","configFile","jsConfig","tsConfig","generateConfig","tailwindInputFile","sourceCode","result","R","userConfig","Buffer","resolveConfig","resolvedConfig","server","file","mod","taroStyleAdapterPlugin","designWidth","maxWidth","baseFontSize","minRootSize","maxRootSize","flexibleScript","rpx2pxPlugin","ratio","decl","_match","num","pxValue","injectTaroEnv","additional","autoInjectTaroApp","autoInjectVite","constants","varsToInject","key","varName","value","injectAmasterEnv","devTools","isTaro","plugins"],"mappings":"2yBAEA,IAAMA,CAAAA,CAAqB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CAAA,CAuB3B,SAASC,CAAAA,CAAuBC,CAAAA,CAAgBC,CAAAA,CAAoB,CAClE,OAAO,CAAA;AAAA;AAAA;AAAA,uBAAA,EAGgBA,CAAU,CAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAA,EAStBD,CAAK,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CA+BlB,CAMO,SAASE,CAAAA,EAA6B,CAC3C,IAAIF,CAAAA,CAAQ,KAAA,CAEZ,OAAO,CACL,IAAA,CAAM,2BAAA,CAEN,eAAeG,CAAAA,CAAQ,CACrBH,EAAQG,CAAAA,CAAO,OAAA,GAAY,QAC7B,CAAA,CAEA,kBAAA,CAAmBC,CAAAA,CAAM,CACvB,GAAI,CAACJ,EAAO,OAAOI,CAAAA,CAEnB,IAAMH,CAAAA,CAAa,OAAA,CAAQ,IAAI,gBAAA,EAAoB,EAAA,CAC7CI,CAAAA,CAAeN,CAAAA,CAAuBC,CAAAA,CAAOC,CAAU,EACv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YAAY,CAAC,EAG5DuE,CAAAA,CAAQ,OAAA,CAAQ,CACd,IAAA,CAAM,2BAAA,CACN,KAAA,CAAO,OAAA,CACP,MAAA,CAAO5E,CAAAA,CAAQ,CACT,OAAOA,CAAAA,CAAO,GAAA,EAAK,OAAA,EAAY,QAAA,EAEjCA,CAAAA,CAAO,KAAK,OAAA,CAAQ,OAAA,EAAS,OAAA,CAAQ0D,CAAAA,EAAc,EAEvD,CACF,CAAC,CAAA,CAAA,CAIC7C,kBAAAA,CAAQ,GAAA,CAAI,kBAAA,EACd+D,CAAAA,CAAQ,IAAA,CAAKnE,CAAAA,EAAmB,EAG3BmE,CACT","file":"index.cjs","sourcesContent":["import type { Plugin } from \"vite\";\n\nconst clickHandlerScript = `<script>\ndocument.addEventListener(\"click\", (e) => {\n const element = e.target;\n const noJumpOut = document.body.classList.contains(\"forbid-jump-out\")\n if (element.hasAttribute(\"data-link-href\") && !noJumpOut) {\n const href = element.getAttribute(\"data-link-href\");\n const target = element.getAttribute(\"data-link-target\");\n if (href) {\n if (target === \"_blank\") {\n window.open(href, \"_blank\");\n } else {\n window.location.href = href;\n }\n }\n } else if(noJumpOut && element.tagName === \"A\") {\n e.preventDefault();\n }\n});\n</script>`;\n\n/**\n * Generate bridge script content with environment variables\n */\nfunction getBridgeScriptContent(isDev: boolean, sessionKey: string) {\n return `<script type=\"module\">\n(function() {\n const SOURCE_KEY = Symbol.for(\"__jsxSource__\");\n const SESSION_KEY = \"${sessionKey}\";\n\n // Expose minimal API for external bridge script\n window.__AMASTER_BRIDGE__ = {\n getSourceInfo: (element) => element?.[SOURCE_KEY],\n getSourceMap: () => window.sourceElementMap,\n postToParent: (type, data) => {\n window.parent.postMessage({ type, data, key: SESSION_KEY }, \"*\");\n },\n isDev: ${isDev},\n };\n\n // Listen for bridge script URL from platform\n window.addEventListener(\"message\", (event) => {\n const { type, data, key } = event.data;\n \n if (key !== SESSION_KEY) {\n console.warn(\"[Bridge] Invalid session key\");\n return;\n }\n \n if (type === \"amaster.loadBridge\" && data?.scriptUrl) {\n const script = document.createElement(\"script\");\n script.src = data.scriptUrl;\n script.onload = () => {\n console.log(\"[Bridge] External script loaded\");\n window.__AMASTER_BRIDGE__?.postToParent(\"amaster.bridge.ready\", {});\n };\n script.onerror = () => {\n console.error(\"[Bridge] Failed to load external script\");\n };\n document.head.appendChild(script);\n }\n });\n\n window.addEventListener(\"load\", () => {\n window.__AMASTER_BRIDGE__?.postToParent(\"amaster.bridge.initialized\", {});\n });\n})();\n</script>`;\n}\n\n/**\n * Vite plugin: Inject editor bridge script\n * Injects minimal bridge that loads external script from platform\n */\nexport function editorBridgePlugin(): Plugin {\n let isDev = false;\n\n return {\n name: \"vite-plugin-editor-bridge\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transformIndexHtml(html) {\n if (!isDev) return html;\n\n const sessionKey = process.env.VITE_AMASTER_KEY || \"\";\n const bridgeScript = getBridgeScriptContent(isDev, sessionKey);\n const scriptsToInject = `${clickHandlerScript}${bridgeScript}</body>`;\n return html.replace(\"</body>\", scriptsToInject);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Vite plugin: Expose routes to window.__APP_ROUTES__\n * Only enabled in development mode\n */\nexport function routesExposePlugin(options?: { routesFilePath?: string }): Plugin {\n let isDev = false;\n const routesPath = options?.routesFilePath || \"src/routes.tsx\";\n\n return {\n name: \"vite-plugin-routes-expose\",\n enforce: \"post\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transform(code: string, id: string) {\n if (!isDev) {\n return null;\n }\n\n if (!id.endsWith(routesPath)) {\n return null;\n }\n\n try {\n if (code.includes(\"window.__APP_ROUTES__\")) {\n return null;\n }\n\n const transformedCode = `${code}\n\n// Development mode: Expose routes to window.__APP_ROUTES__\nif (typeof window !== 'undefined') {\n window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];\n}\n`;\n\n return {\n code: transformedCode,\n map: null,\n };\n } catch {\n return null;\n }\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport { Buffer } from \"node:buffer\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\n/**\n * Browser logs collection plugin\n * Injects script into HTML head to collect console logs and network requests\n * Logs are written directly to browser.log file (same level as index.html)\n */\nexport function browserLogsPlugin(): Plugin {\n let logFilePath = \"\";\n\n // Script to inject into browser\n const injectedScript = `\n<script>\n(function() {\n 'use strict';\n \n // Log API path (provided by Vite dev server)\n var LOG_API_PATH = '/__browser__';\n \n // Write queue to ensure sequential writes\n var writeQueue = [];\n var isWriting = false;\n \n // Process write queue to ensure sequential writes\n function processWriteQueue() {\n if (isWriting || writeQueue.length === 0) return;\n \n isWriting = true;\n var entry = writeQueue.shift();\n var logText = JSON.stringify(entry);\n \n fetch(LOG_API_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: logText\n })\n .then(function(response) {\n isWriting = false;\n if (!response.ok) {\n console.warn('[BrowserLogs] Failed to write log:', response.status);\n }\n // Continue processing next item in queue\n processWriteQueue();\n })\n .catch(function(error) {\n console.warn('[BrowserLogs] Failed to write log:', error.message);\n // On failure, put log back to queue head for retry\n writeQueue.unshift(entry);\n isWriting = false;\n // Retry after delay\n setTimeout(processWriteQueue, 1000);\n });\n }\n \n // Limit headers object size\n function truncateHeaders(headers) {\n if (!headers) return headers;\n var jsonStr = JSON.stringify(headers);\n if (jsonStr.length <= MAX_HEADER_SIZE) return headers;\n return '[Headers truncated, size: ' + jsonStr.length + ']';\n }\n \n // Truncate oversized log entries\n function truncateLogEntry(entry) {\n var jsonStr = JSON.stringify(entry);\n if (jsonStr.length <= MAX_LOG_ENTRY_SIZE) {\n return entry;\n }\n \n // If oversized, progressively truncate non-critical fields\n var truncated = Object.assign({}, entry);\n \n // 1. Truncate response body first\n if (truncated.responseBody && typeof truncated.responseBody === 'string') {\n truncated.responseBody = truncated.responseBody.substring(0, 500) + '... [truncated]';\n }\n \n // 2. Truncate request body\n if (truncated.requestBody && typeof truncated.requestBody === 'string') {\n truncated.requestBody = truncated.requestBody.substring(0, 500) + '... [truncated]';\n }\n \n // 3. Truncate message\n if (truncated.message && typeof truncated.message === 'string' && truncated.message.length > 1000) {\n truncated.message = truncated.message.substring(0, 1000) + '... [truncated]';\n }\n \n // 4. Truncate stack\n if (truncated.stack && Array.isArray(truncated.stack) && truncated.stack.length > 3) {\n truncated.stack = truncated.stack.slice(0, 3);\n }\n \n // Add truncation marker\n truncated._truncated = true;\n truncated._originalSize = jsonStr.length;\n \n return truncated;\n }\n \n // Add log and send immediately (ensure order)\n function addLog(entry) {\n var truncatedEntry = truncateLogEntry(entry);\n writeQueue.push(truncatedEntry);\n processWriteQueue();\n }\n \n // ============================================\n // Console log collection\n // ============================================\n var originalConsole = {\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error,\n debug: console.debug\n };\n \n function getStackTrace() {\n var stack = new Error().stack || '';\n var lines = stack.split('\\\\n').slice(3);\n // Limit stack lines\n return lines.slice(0, MAX_STACK_LINES).map(function(line) { return line.trim(); });\n }\n \n function formatMessage(args) {\n return Array.from(args).map(function(arg) {\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg);\n } catch (e) {\n return String(arg);\n }\n }\n return String(arg);\n }).join(' ');\n }\n \n function createLogEntry(level, args) {\n return {\n type: 'console',\n timestamp: new Date().toISOString(),\n level: level,\n message: formatMessage(args),\n stack: getStackTrace()\n };\n }\n \n // Check if message should be filtered (contains [vite] text)\n function shouldFilterConsoleLog(args) {\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n if (typeof arg === 'string' && arg.indexOf('[vite]') !== -1) {\n return true;\n }\n }\n return false;\n }\n \n function wrapConsoleMethod(method, level) {\n return function() {\n var args = arguments;\n // Filter out logs containing [vite]\n if (shouldFilterConsoleLog(args)) {\n return originalConsole[method].apply(console, args);\n }\n var entry = createLogEntry(level, args);\n addLog(entry);\n return originalConsole[method].apply(console, args);\n };\n }\n \n console.log = wrapConsoleMethod('log', 'log');\n console.info = wrapConsoleMethod('info', 'info');\n console.warn = wrapConsoleMethod('warn', 'warn');\n console.error = wrapConsoleMethod('error', 'error');\n console.debug = wrapConsoleMethod('debug', 'debug');\n \n // ============================================\n // Network request collection (exclude SSE and log API requests)\n // ============================================\n \n var MAX_BODY_SIZE = 2000;\n var MAX_LOG_ENTRY_SIZE = 3000; // Max single log entry length\n var MAX_HEADER_SIZE = 500; // Max single header object length\n var MAX_STACK_LINES = 5; // Max stack lines to keep\n const FILTERED_URLS = ['/__browser__', '/builtin']; // Filter out log API and Vite built-in requests\n \n function isSSERequest(url, headers) {\n var sseUrlPatterns = ['/events', '/sse', '/stream', 'text/event-stream'];\n var urlStr = String(url).toLowerCase();\n for (var i = 0; i < sseUrlPatterns.length; i++) {\n if (urlStr.indexOf(sseUrlPatterns[i]) !== -1) {\n return true;\n }\n }\n \n if (headers) {\n if (typeof headers.get === 'function') {\n var accept = headers.get('Accept') || headers.get('accept');\n if (accept && accept.indexOf('text/event-stream') !== -1) {\n return true;\n }\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n if (key.toLowerCase() === 'accept' && headers[key].indexOf('text/event-stream') !== -1) {\n return true;\n }\n }\n }\n }\n \n return false;\n }\n \n function shouldFilterRequest(url) {\n return FILTERED_URLS.some(function(filteredUrl) {\n return String(url).indexOf(filteredUrl) !== -1;\n });\n }\n \n function formatRequestBody(body) {\n if (!body) return null;\n \n try {\n if (typeof body === 'string') {\n return body.substring(0, MAX_BODY_SIZE);\n }\n if (body instanceof FormData) {\n var formDataObj = {};\n body.forEach(function(value, key) {\n if (value instanceof File) {\n formDataObj[key] = '[File: ' + value.name + ', size: ' + value.size + ']';\n } else {\n formDataObj[key] = String(value).substring(0, 1000);\n }\n });\n return JSON.stringify(formDataObj);\n }\n if (body instanceof Blob) {\n return '[Blob: size=' + body.size + ', type=' + body.type + ']';\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return '[Binary: size=' + body.byteLength + ']';\n }\n if (body instanceof URLSearchParams) {\n return body.toString().substring(0, MAX_BODY_SIZE);\n }\n return String(body).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading body: ' + e.message + ']';\n }\n }\n \n function formatResponseBody(response, responseType) {\n if (!response) return null;\n \n try {\n if (responseType === '' || responseType === 'text') {\n return String(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'json') {\n return JSON.stringify(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'document') {\n return '[Document]';\n }\n if (responseType === 'blob') {\n return '[Blob: size=' + response.size + ']';\n }\n if (responseType === 'arraybuffer') {\n return '[ArrayBuffer: size=' + response.byteLength + ']';\n }\n return String(response).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading response: ' + e.message + ']';\n }\n }\n \n // Intercept XMLHttpRequest\n var originalXHROpen = XMLHttpRequest.prototype.open;\n var originalXHRSend = XMLHttpRequest.prototype.send;\n var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;\n \n XMLHttpRequest.prototype.open = function(method, url, async, user, password) {\n this.__requestInfo__ = {\n method: method,\n url: url,\n startTime: null,\n headers: {}\n };\n return originalXHROpen.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.setRequestHeader = function(name, value) {\n if (this.__requestInfo__ && this.__requestInfo__.headers) {\n this.__requestInfo__.headers[name] = value;\n }\n return originalXHRSetRequestHeader.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.send = function(body) {\n var xhr = this;\n var requestInfo = xhr.__requestInfo__;\n \n if (requestInfo) {\n // Skip SSE requests and filtered requests\n if (isSSERequest(requestInfo.url, requestInfo.headers) || shouldFilterRequest(requestInfo.url)) {\n return originalXHRSend.apply(this, arguments);\n }\n \n requestInfo.startTime = Date.now();\n requestInfo.requestBody = formatRequestBody(body);\n \n xhr.addEventListener('loadend', function() {\n var contentType = xhr.getResponseHeader('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return;\n }\n \n var responseHeaders = {};\n var allHeaders = xhr.getAllResponseHeaders();\n if (allHeaders) {\n allHeaders.split('\\\\r\\\\n').forEach(function(line) {\n var parts = line.split(': ');\n if (parts.length === 2) {\n responseHeaders[parts[0]] = parts[1];\n }\n });\n }\n \n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'xhr',\n method: requestInfo.method,\n url: requestInfo.url,\n status: xhr.status,\n statusText: xhr.statusText,\n duration: Date.now() - requestInfo.startTime,\n requestHeaders: truncateHeaders(requestInfo.headers),\n requestBody: requestInfo.requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseType: xhr.responseType,\n responseBody: formatResponseBody(xhr.response, xhr.responseType),\n responseSize: xhr.response ? (typeof xhr.response === 'string' ? xhr.response.length : (xhr.response.byteLength || xhr.response.size || null)) : null\n };\n \n addLog(entry);\n });\n }\n \n return originalXHRSend.apply(this, arguments);\n };\n \n // Intercept Fetch API\n var originalFetch = window.fetch;\n \n function headersToObject(headers) {\n var obj = {};\n if (!headers) return obj;\n \n if (typeof headers.forEach === 'function') {\n headers.forEach(function(value, key) {\n obj[key] = value;\n });\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n obj[key] = headers[key];\n }\n }\n return obj;\n }\n \n window.fetch = function(input, init) {\n var startTime = Date.now();\n var method = (init && init.method) || 'GET';\n var url = typeof input === 'string' ? input : input.url;\n var headers = init && init.headers;\n \n // Skip SSE requests and filtered requests\n if (isSSERequest(url, headers) || shouldFilterRequest(url)) {\n return originalFetch.apply(this, arguments);\n }\n \n var requestHeaders = headersToObject(headers);\n var requestBody = formatRequestBody(init && init.body);\n \n return originalFetch.apply(this, arguments)\n .then(function(response) {\n var contentType = response.headers.get('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return response;\n }\n \n var clonedResponse = response.clone();\n var responseHeaders = headersToObject(response.headers);\n \n clonedResponse.text().then(function(bodyText) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: bodyText ? bodyText.substring(0, MAX_BODY_SIZE) : null,\n responseSize: bodyText ? bodyText.length : null,\n ok: response.ok\n };\n \n addLog(entry);\n }).catch(function(e) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: '[Unable to read: ' + e.message + ']',\n responseSize: null,\n ok: response.ok\n };\n \n addLog(entry);\n });\n \n return response;\n })\n .catch(function(error) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: 0,\n statusText: 'Network Error',\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: null,\n responseBody: null,\n error: error.message\n };\n \n addLog(entry);\n throw error;\n });\n };\n \n // ============================================\n // Global error capture\n // ============================================\n window.addEventListener('error', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: event.message,\n stack: event.error ? event.error.stack : 'at ' + event.filename + ':' + event.lineno + ':' + event.colno\n };\n addLog(entry);\n });\n \n // ============================================\n // Vite deps 504 error capture using PerformanceObserver\n // Only captures 504 errors for node_modules/.vite resources (pre-bundled dependencies)\n // ============================================\n var reportedUrls = {}; // Track reported URLs to avoid duplicates\n \n if (typeof PerformanceObserver !== 'undefined') {\n var perfObserver = new PerformanceObserver(function(list) {\n var entries = list.getEntries();\n for (var i = 0; i < entries.length; i++) {\n var perfEntry = entries[i];\n // Only check script resources\n if (perfEntry.initiatorType !== 'script') {\n continue;\n }\n \n var resourceUrl = perfEntry.name || '';\n // Only report errors for node_modules/.vite resources\n if (resourceUrl.indexOf('node_modules/.vite') === -1 && resourceUrl.indexOf('/node_modules/.vite') === -1) {\n continue;\n }\n \n // Check if response status is 504 (Gateway Timeout)\n // responseStatus is available in Resource Timing Level 2\n var status = perfEntry.responseStatus;\n if (status === 504) {\n // Avoid duplicate reports\n if (reportedUrls[resourceUrl]) {\n continue;\n }\n reportedUrls[resourceUrl] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: resourceUrl,\n status: 504,\n message: 'Vite pre-bundled dependency returned 504 Gateway Timeout: ' + resourceUrl,\n duration: perfEntry.duration,\n transferSize: perfEntry.transferSize\n };\n addLog(entry);\n }\n }\n });\n \n try {\n perfObserver.observe({ type: 'resource', buffered: true });\n } catch (e) {\n // Fallback for browsers that don't support the options\n try {\n perfObserver.observe({ entryTypes: ['resource'] });\n } catch (e2) {\n originalConsole.warn('[BrowserLogs] PerformanceObserver not supported:', e2.message);\n }\n }\n }\n \n // ============================================\n // Script load error capture (for 504 and other network errors)\n // This captures errors that PerformanceObserver might miss\n // ============================================\n \n // Use MutationObserver to watch for dynamically added script tags\n function attachScriptErrorHandler(script) {\n if (script.__errorHandlerAttached__) return;\n script.__errorHandlerAttached__ = true;\n \n script.addEventListener('error', function(event) {\n var src = script.src || '';\n \n // Only report errors for node_modules/.vite resources\n if (src.indexOf('node_modules/.vite') === -1 && src.indexOf('/node_modules/.vite') === -1) {\n return;\n }\n \n // Avoid duplicate reports\n if (reportedUrls[src]) {\n return;\n }\n reportedUrls[src] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: src,\n status: 'load-error',\n message: 'Vite pre-bundled dependency failed to load (possibly 504 Gateway Timeout): ' + src,\n errorType: event.type\n };\n addLog(entry);\n });\n }\n \n // Attach error handlers to existing scripts\n var existingScripts = document.querySelectorAll('script[src]');\n for (var i = 0; i < existingScripts.length; i++) {\n attachScriptErrorHandler(existingScripts[i]);\n }\n \n // Watch for dynamically added scripts\n if (typeof MutationObserver !== 'undefined') {\n var scriptObserver = new MutationObserver(function(mutations) {\n for (var i = 0; i < mutations.length; i++) {\n var mutation = mutations[i];\n for (var j = 0; j < mutation.addedNodes.length; j++) {\n var node = mutation.addedNodes[j];\n if (node.nodeName === 'SCRIPT' && node.src) {\n attachScriptErrorHandler(node);\n }\n // Also check child nodes\n if (node.querySelectorAll) {\n var scripts = node.querySelectorAll('script[src]');\n for (var k = 0; k < scripts.length; k++) {\n attachScriptErrorHandler(scripts[k]);\n }\n }\n }\n }\n });\n \n scriptObserver.observe(document.documentElement, {\n childList: true,\n subtree: true\n });\n }\n \n // Also intercept document.createElement to catch scripts before they're added to DOM\n var originalCreateElement = document.createElement.bind(document);\n document.createElement = function(tagName) {\n var element = originalCreateElement(tagName);\n if (tagName.toLowerCase() === 'script') {\n // Use a setter to catch when src is set\n var originalSrc = '';\n Object.defineProperty(element, '__originalSrc__', {\n get: function() { return originalSrc; },\n set: function(val) { originalSrc = val; }\n });\n \n // Defer attaching error handler until src is set\n var srcDescriptor = Object.getOwnPropertyDescriptor(HTMLScriptElement.prototype, 'src');\n if (srcDescriptor && srcDescriptor.set) {\n var originalSrcSetter = srcDescriptor.set;\n Object.defineProperty(element, 'src', {\n get: function() {\n return srcDescriptor.get ? srcDescriptor.get.call(this) : this.getAttribute('src');\n },\n set: function(value) {\n if (originalSrcSetter) {\n originalSrcSetter.call(this, value);\n } else {\n this.setAttribute('src', value);\n }\n attachScriptErrorHandler(this);\n },\n configurable: true\n });\n }\n }\n return element;\n };\n \n window.addEventListener('unhandledrejection', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),\n stack: event.reason && event.reason.stack ? event.reason.stack : ''\n };\n addLog(entry);\n });\n \n // ============================================\n // Send remaining logs on page unload\n // ============================================\n window.addEventListener('beforeunload', function() {\n if (writeQueue.length > 0) {\n // Use sendBeacon to ensure logs are sent\n writeQueue.forEach(function(entry) {\n navigator.sendBeacon(LOG_API_PATH, JSON.stringify(entry));\n });\n writeQueue = [];\n }\n });\n \n // ============================================\n // Provide manual flush method\n // ============================================\n window.__flushBrowserLogs__ = function() {\n return new Promise(function(resolve) {\n // Wait for queue to finish processing\n function checkQueue() {\n if (writeQueue.length === 0 && !isWriting) {\n resolve();\n } else {\n setTimeout(checkQueue, 100);\n }\n }\n checkQueue();\n });\n };\n \n // Provide method to get queue status\n window.__getBrowserLogsStatus__ = function() {\n return {\n queueLength: writeQueue.length,\n isWriting: isWriting\n };\n };\n \n originalConsole.log('[BrowserLogs] Log collection started');\n})();\n</script>`;\n\n return {\n name: \"vite-plugin-browser-logs\",\n\n configResolved(config) {\n // Determine log file path: use WORKSPACE_DIR env var (set by PM2/Docker),\n // or find the nearest directory containing package.json from config.root,\n // to ensure browser.log is always at the workspace root level.\n const workspaceDir = process.env.WORKSPACE_DIR;\n if (workspaceDir) {\n logFilePath = path.join(workspaceDir, \"browser.log\");\n } else {\n // Fallback: walk up from config.root to find directory with package.json\n let dir = config.root || process.cwd();\n while (dir !== path.dirname(dir)) {\n if (fs.existsSync(path.join(dir, \"package.json\"))) {\n break;\n }\n dir = path.dirname(dir);\n }\n logFilePath = path.join(dir, \"browser.log\");\n }\n },\n\n configureServer(devServer) {\n // Add log write API\n devServer.middlewares.use((req, res, next) => {\n if (req.url === \"/__browser__\" && req.method === \"POST\") {\n // Get request origin, dynamically set CORS headers to avoid protocol mismatch\n const origin = req.headers.origin || \"*\";\n\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n try {\n // Ensure log directory exists\n const logDir = path.dirname(logFilePath);\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n // Append to log file\n fs.appendFileSync(logFilePath, `${body}\\n`, \"utf-8\");\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: true }));\n } catch (error) {\n console.error(\"[BrowserLogs] Write error:\", error);\n res.writeHead(500, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: false, error: String(error) }));\n }\n });\n } else if (req.url === \"/__browser__\" && req.method === \"OPTIONS\") {\n // Handle CORS preflight request\n const origin = req.headers.origin || \"*\";\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n res.end();\n } else if (req.url === \"/__browser__\") {\n const origin = req.headers.origin || \"*\";\n res.writeHead(405, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n });\n res.end(JSON.stringify({ error: \"Method not allowed\" }));\n } else {\n next();\n }\n });\n\n console.log(\"[BrowserLogs] Logs will be written to:\", logFilePath);\n },\n\n transformIndexHtml(html) {\n // Insert script after <head> tag to ensure earliest execution\n return html.replace(/<head([^>]*)>/i, `<head$1>${injectedScript}`);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Runtime code that will be injected to replace react/jsx-dev-runtime\n * This code tags DOM elements with source information using refs\n */\nconst devRuntimeCode = `\nimport * as React from \"react\";\nimport * as ReactJSXDevRuntime from \"react/jsx-dev-runtime\";\n\nconst _jsxDEV = ReactJSXDevRuntime.jsxDEV;\nexport const Fragment = ReactJSXDevRuntime.Fragment;\n\nconst SOURCE_KEY = Symbol.for(\"__jsxSource__\");\nconst PROJECT_ROOT = \"\";\n\nconst cleanFileName = (fileName) => {\n if (!fileName) return \"\";\n // Remove project root prefix to get relative path\n if (PROJECT_ROOT && fileName.startsWith(PROJECT_ROOT)) {\n const relative = fileName.slice(PROJECT_ROOT.length);\n return relative.startsWith(\"/\") ? relative.slice(1) : relative;\n }\n return fileName;\n};\n\n// Global map to track elements by source location\nconst sourceElementMap = new Map();\nwindow.sourceElementMap = sourceElementMap;\n\nfunction getSourceKey(sourceInfo) {\n return \\`\\${cleanFileName(sourceInfo.fileName)}:\\${sourceInfo.lineNumber}:\\${sourceInfo.columnNumber}\\`;\n}\n\nfunction unregisterElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n const refs = sourceElementMap.get(key);\n if (refs) {\n for (const ref of refs) {\n if (ref.deref() === node) {\n refs.delete(ref);\n break;\n }\n }\n if (refs.size === 0) {\n sourceElementMap.delete(key);\n }\n }\n}\n\nfunction registerElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n if (!sourceElementMap.has(key)) {\n sourceElementMap.set(key, new Set());\n }\n sourceElementMap.get(key).add(new WeakRef(node));\n}\n\nfunction getTypeName(type) {\n if (typeof type === \"string\") return type;\n if (typeof type === \"function\") return type.displayName || type.name || \"Unknown\";\n if (typeof type === \"object\" && type !== null) {\n return type.displayName || type.render?.displayName || type.render?.name || \"Unknown\";\n }\n return \"Unknown\";\n}\n\nexport function jsxDEV(type, props, key, isStatic, source, self) {\n // For custom components, tag their rendered output\n if (source?.fileName && typeof type !== \"string\" && type !== Fragment) {\n const typeName = getTypeName(type);\n const jsxSourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: typeName,\n };\n\n const originalRef = props?.ref;\n \n // Check if component can safely receive refs\n // - forwardRef components have $$typeof symbol\n // - Class components have prototype.isReactComponent\n // - If there's already a ref, the component expects it\n const isForwardRef = type.$$typeof === Symbol.for('react.forward_ref');\n const isClassComponent = typeof type === 'function' && type.prototype?.isReactComponent;\n const hasExistingRef = originalRef !== undefined;\n \n const canReceiveRef = isForwardRef || isClassComponent || hasExistingRef;\n \n if (canReceiveRef) {\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n if (!node[SOURCE_KEY]) {\n node[SOURCE_KEY] = jsxSourceInfo;\n registerElement(node, jsxSourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n }\n\n // For host elements (div, span, etc.), tag with source info\n if (source?.fileName && typeof type === \"string\") {\n const sourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: type,\n };\n\n const originalRef = props?.ref;\n\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n const existingSource = node[SOURCE_KEY];\n if (existingSource) {\n if (getSourceKey(existingSource) !== getSourceKey(sourceInfo)) {\n unregisterElement(node, existingSource);\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n } else {\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n}\n`;\n\n/**\n * Vite plugin: JSX Source Tagger\n * Intercepts react/jsx-dev-runtime to add source information to DOM elements\n * Only enabled in development mode\n */\nexport function jsxSourceTaggerPlugin(): Plugin {\n let isDev = false;\n let projectRoot = \"\";\n\n return {\n name: \"vite-plugin-jsx-source-tagger\",\n enforce: \"pre\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n projectRoot = config.root;\n },\n\n resolveId(id, importer) {\n if (!isDev) return null;\n\n // Intercept react/jsx-dev-runtime imports\n if (id === \"react/jsx-dev-runtime\" && !importer?.includes(\"\\0jsx-source\")) {\n return \"\\0jsx-source/jsx-dev-runtime\";\n }\n return null;\n },\n\n load(id) {\n if (!isDev) return null;\n\n // Return our custom runtime code with injected projectRoot\n if (id === \"\\0jsx-source/jsx-dev-runtime\") {\n return devRuntimeCode.replace(\n 'const PROJECT_ROOT = \"\";',\n `const PROJECT_ROOT = ${JSON.stringify(projectRoot)};`\n );\n }\n return null;\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport * as esbuild from \"esbuild\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Vite plugin: Tailwind Config Sync\n * Generates a JSON file from tailwind.config.ts for runtime access\n * Only enabled in development mode\n */\nexport function tailwindConfigSyncPlugin(options?: { configPath?: string }): Plugin {\n let projectRoot = \"\";\n let isDev = false;\n let cachedConfig: Record<string, unknown> | null = null;\n\n const configPath = options?.configPath || \"./tailwind.config.ts\";\n const VIRTUAL_MODULE_ID = \"@amaster/tailwind-config\";\n const RESOLVED_VIRTUAL_MODULE_ID = \"\\0\" + VIRTUAL_MODULE_ID;\n\n const findConfigFile = async (): Promise<string | null> => {\n const configFile = path.resolve(projectRoot, configPath);\n\n try {\n await fs.access(configFile);\n return configFile;\n } catch {\n // If specified config doesn't exist, try alternative extensions\n if (configPath.endsWith(\".ts\")) {\n const jsConfig = configFile.replace(/\\.ts$/, \".js\");\n try {\n await fs.access(jsConfig);\n return jsConfig;\n } catch {\n return null;\n }\n } else if (configPath.endsWith(\".js\")) {\n const tsConfig = configFile.replace(/\\.js$/, \".ts\");\n try {\n await fs.access(tsConfig);\n return tsConfig;\n } catch {\n return null;\n }\n }\n return null;\n }\n };\n\n const generateConfig = async (): Promise<Record<string, unknown> | null> => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (!tailwindInputFile) return null;\n\n const sourceCode = await fs.readFile(tailwindInputFile, \"utf-8\");\n const result = await esbuild.transform(sourceCode, {\n loader: tailwindInputFile.endsWith(\".ts\") ? \"ts\" : \"js\",\n format: \"esm\",\n platform: \"node\",\n });\n\n const dataUrl = `data:text/javascript;base64,${Buffer.from(result.code).toString(\"base64\")}`;\n const userConfig = await import(dataUrl);\n\n if (!userConfig?.default) {\n throw new Error(\"Invalid Tailwind config structure\");\n }\n\n // Try to resolve with tailwindcss, fallback to raw config\n try {\n const resolveConfig = (await import(\"tailwindcss/resolveConfig.js\")).default;\n cachedConfig = resolveConfig(userConfig.default);\n } catch {\n cachedConfig = userConfig.default;\n }\n\n return cachedConfig;\n } catch {\n return null;\n }\n };\n\n return {\n name: \"vite-plugin-tailwind-config-sync\",\n\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n isDev = resolvedConfig.command === \"serve\";\n },\n\n async buildStart() {\n if (!isDev) return;\n await generateConfig();\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return RESOLVED_VIRTUAL_MODULE_ID;\n }\n },\n\n async load(id) {\n if (id === RESOLVED_VIRTUAL_MODULE_ID) {\n if (!cachedConfig) {\n await generateConfig();\n }\n\n // Generate code with HMR support\n const code = `\nlet config = ${JSON.stringify(cachedConfig)};\n\nlet _updateConfig;\nif (import.meta.hot) {\n // Accept self updates\n import.meta.hot.accept((newModule) => {\n if (newModule && _updateConfig) {\n _updateConfig(newModule.default);\n }\n });\n}\n\nexport default new Proxy(config, {\n get(target, prop) {\n if (prop === 'then') return undefined;\n if (prop === '__setUpdater') {\n return (fn) => { _updateConfig = fn; };\n }\n return target[prop];\n }\n});\n`;\n return code;\n }\n },\n\n configureServer(server) {\n if (!isDev) return;\n\n (async () => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (tailwindInputFile) {\n server.watcher.add(tailwindInputFile);\n }\n } catch {\n // Ignore errors\n }\n })();\n },\n\n async handleHotUpdate({ file, server }) {\n const tailwindInputFile = await findConfigFile();\n\n if (!tailwindInputFile || path.normalize(file) !== path.normalize(tailwindInputFile)) {\n return;\n }\n\n await generateConfig();\n\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n return [mod];\n }\n\n return [];\n },\n };\n}\n","import type { Plugin } from 'vite';\n\nexport interface TaroStyleAdapterOptions {\n /**\n * Design width for responsive scaling (default: 375)\n * Should match Taro config's designWidth\n */\n designWidth?: number;\n \n /**\n * Maximum viewport width to scale (default: 750)\n * Beyond this width, font-size stays fixed\n */\n maxWidth?: number;\n\n /**\n * Base font size in pixels (default: 12)\n * Should match Taro config's baseFontSize\n */\n baseFontSize?: number;\n\n /**\n * Minimum root font size in pixels (default: 12)\n * Should match Taro config's minRootSize\n */\n minRootSize?: number;\n\n /**\n * Maximum root font size in pixels (default: 24)\n * Should match Taro config's maxRootSize\n */\n maxRootSize?: number;\n}\n\n/**\n * Taro H5 样式适配插件\n * \n * 功能:\n * 1. 动态计算根字号,使 H5 的 rem 与小程序的 rpx 行为对齐\n * 2. 隐藏 Taro 页面容器的滚动条,用于编辑器 iframe 预览\n * \n * 原理:\n * - 小程序 rpx: 1rpx = 屏幕宽度 / 750\n * - H5 rem: Taro 把 rpx 转成 rem,基于 baseFontSize\n * - 本插件动态设置 html font-size,使 rem 的实际像素值与 rpx 对齐\n * \n * 注意:此插件会覆盖 Taro 默认注入的根字号脚本,配置需与 Taro pxtransform 保持一致\n * \n * @example\n * ```ts\n * // In Taro config/dev.ts\n * import { taroStyleAdapterPlugin } from '@amaster.ai/vite-plugins'\n * \n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [\n * taroStyleAdapterPlugin({ \n * designWidth: 375,\n * baseFontSize: 12,\n * minRootSize: 12,\n * maxRootSize: 24\n * })\n * ]\n * }\n * }\n * ```\n */\nexport function taroStyleAdapterPlugin(options: TaroStyleAdapterOptions = {}): Plugin {\n const { \n designWidth = 375, \n maxWidth = 750,\n baseFontSize = 12,\n minRootSize = 12,\n maxRootSize = 24\n } = options;\n \n return {\n name: 'vite-plugin-taro-style-adapter',\n apply: 'serve', // 仅在开发模式下生效\n transformIndexHtml(html) {\n // 动态根字号脚本\n // 公式:fontSize = (clientWidth / designWidth) * baseFontSize\n // 当 designWidth=375, baseFontSize=12 时:\n // - 375px 屏幕 → 12px (1rem = 12px)\n // - 750px 屏幕 → 24px (1rem = 24px)\n // 这样 rem 值在不同屏幕宽度下的视觉比例与小程序 rpx 一致\n const flexibleScript = `\n<script data-taro-flexible=\"true\">\n(function() {\n var designWidth = ${designWidth};\n var maxWidth = ${maxWidth};\n var baseFontSize = ${baseFontSize};\n var minRootSize = ${minRootSize};\n var maxRootSize = ${maxRootSize};\n \n function setRootFontSize() {\n var docEl = document.documentElement;\n var clientWidth = docEl.clientWidth;\n \n // 限制最大宽度\n if (clientWidth > maxWidth) {\n clientWidth = maxWidth;\n }\n \n // 计算根字号: (屏幕宽度 / 设计稿宽度) * 基准字号\n var fontSize = (clientWidth / designWidth) * baseFontSize;\n \n // 应用最小/最大限制\n if (fontSize < minRootSize) {\n fontSize = minRootSize;\n } else if (fontSize > maxRootSize) {\n fontSize = maxRootSize;\n }\n \n docEl.style.fontSize = fontSize + 'px';\n }\n \n setRootFontSize();\n \n // 监听窗口变化\n window.addEventListener('resize', setRootFontSize);\n window.addEventListener('orientationchange', setRootFontSize);\n \n // 页面显示时重新计算(解决某些浏览器的 bug)\n document.addEventListener('DOMContentLoaded', setRootFontSize);\n})();\n</script>\n`;\n\n // 滚动条隐藏样式 + Taro Image 组件修复\n const styles = `\n<style data-taro-adapter=\"true\">\n /* 仅 H5 生效:隐藏 Taro 页面容器滚动条,但仍可滚动 */\n .taro_page {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro_page::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /* 隐藏 Taro ScrollView 组件的滚动条 */\n .taro-scroll-view__scroll-y,\n .taro-scroll-view__scroll-x {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro-scroll-view__scroll-y::-webkit-scrollbar,\n .taro-scroll-view__scroll-x::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /*\n * 修复 Taro Image 组件在 H5 下的尺寸问题\n * \n * 问题:Taro Image 组件使用 aspectFit 模式时,内部 img 使用 max-width/max-height: 100%\n * 导致小尺寸图片(如 SVG 图标)无法按指定尺寸显示,只显示原始尺寸\n * \n * 解决:让 img 填满 taro-image-core 容器,由容器控制尺寸\n */\n taro-image-core img.taro-img__mode-aspectfit {\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n position: static;\n transform: none;\n object-fit: contain;\n }\n</style>\n`;\n \n // 在 </head> 之前插入脚本和样式\n return html.replace('</head>', `${flexibleScript}${styles}</head>`);\n }\n };\n}\n","/**\n * PostCSS 插件:H5 模式下将 rpx 预转换为 px\n *\n * 问题背景:\n * - Taro 的 pxtransform 在 H5 模式下会处理 rpx,但它把 rpx 值直接除以 rootValue\n * - 导致 96rpx 被转成 8rem(96/12),实际显示为 96px\n * - 而正确应该是:96rpx = 48px = 4rem = 48px\n *\n * 解决方案:\n * - 在 pxtransform 之前,先把 rpx 转成 px(rpx / 2)\n * - 然后 pxtransform 会正确地把 px 转成 rem(px / 12)\n *\n * 转换链路:96rpx → 48px → 4rem → 48px(正确)\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { rpx2pxPlugin } from '@amaster.ai/vite-plugins'\n * \n * // 在 postcss-config-loader-plugin 中使用\n * {\n * name: 'postcss-config-loader-plugin',\n * config(config) {\n * if (typeof config.css?.postcss === 'object') {\n * config.css?.postcss.plugins?.unshift(tailwindcss())\n * // H5 模式下添加 rpx2px 插件\n * if (process.env.TARO_ENV === 'h5') {\n * config.css?.postcss.plugins?.unshift(rpx2pxPlugin())\n * }\n * }\n * }\n * }\n * ```\n */\n\nexport interface Rpx2pxPluginOptions {\n /**\n * rpx 到 px 的转换比例(默认 2)\n * 即 1rpx = 1/ratio px\n * 默认值 2 表示 2rpx = 1px(基于 375 设计稿)\n */\n ratio?: number;\n}\n\ninterface PostCSSDeclaration {\n value: string;\n}\n\ninterface PostCSSPlugin {\n postcssPlugin: string;\n Declaration: (decl: PostCSSDeclaration) => void;\n}\n\ntype PostCSSPluginCreator = {\n (): PostCSSPlugin;\n postcss: boolean;\n};\n\nexport function rpx2pxPlugin(options: Rpx2pxPluginOptions = {}): PostCSSPlugin {\n const { ratio = 2 } = options;\n \n return {\n postcssPlugin: 'postcss-rpx2px',\n Declaration(decl: PostCSSDeclaration) {\n if (decl.value.includes('rpx')) {\n decl.value = decl.value.replace(/(-?\\d*\\.?\\d+)rpx/gi, (_match: string, num: string) => {\n const pxValue = parseFloat(num) / ratio;\n return pxValue === 0 ? '0' : `${pxValue}px`;\n });\n }\n }\n };\n}\n\n// PostCSS 插件标识\n(rpx2pxPlugin as PostCSSPluginCreator).postcss = true;\n","/**\n * Taro Environment Variables Injection Helper\n * \n * Automatically injects environment variables into Taro's defineConstants\n * so that they will be replaced at build time.\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { injectTaroEnv } from '@amaster.ai/vite-plugins/taro-env-inject'\n * \n * export default defineConfig({\n * defineConstants: {\n * ...injectTaroEnv()\n * }\n * })\n * ```\n */\n\nexport interface TaroEnvInjectOptions {\n /**\n * Additional environment variable names to inject\n * @default []\n */\n additional?: string[];\n \n /**\n * Whether to inject all TARO_APP_* prefixed variables\n * @default true\n */\n autoInjectTaroApp?: boolean;\n \n /**\n * Whether to inject all VITE_* prefixed variables\n * @default true\n */\n autoInjectVite?: boolean;\n}\n\n/**\n * Inject environment variables into Taro's defineConstants\n * \n * This function reads environment variables and formats them for Taro's defineConstants.\n * Taro will replace these at build time, converting `process.env.XXX` to actual values.\n */\nexport function injectTaroEnv(options: TaroEnvInjectOptions = {}): Record<string, string> {\n const {\n additional = [],\n autoInjectTaroApp = true,\n autoInjectVite = true,\n } = options;\n\n const constants: Record<string, string> = {};\n\n // Collect variable names to inject\n const varsToInject = new Set<string>(additional);\n\n // Auto-detect TARO_APP_* variables\n if (autoInjectTaroApp) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('TARO_APP_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Auto-detect VITE_* variables\n if (autoInjectVite) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('VITE_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Inject variables into defineConstants format\n varsToInject.forEach(varName => {\n const value = process.env[varName] || '';\n constants[`process.env.${varName}`] = JSON.stringify(value);\n });\n\n return constants;\n}\n\n/**\n * Inject specific environment variables for amaster.ai mini-program builds\n * \n * This is a convenience function that injects the standard environment variables\n * used by @amaster.ai/http-client for API base URL configuration.\n */\nexport function injectAmasterEnv(): Record<string, string> {\n return {\n 'process.env.TARO_APP_API_BASE_URL': JSON.stringify(process.env.TARO_APP_API_BASE_URL || ''),\n 'process.env.VITE_API_BASE_URL': JSON.stringify(process.env.VITE_API_BASE_URL || ''),\n };\n}\n","import { editorBridgePlugin } from \"./editor-bridge\";\nimport { routesExposePlugin } from \"./routes-expose\";\nimport { browserLogsPlugin } from \"./browser-logs\";\nimport { jsxSourceTaggerPlugin } from \"./tagger\";\nimport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n// import { smartReloadPlugin } from \"./smart-reload\"; // 智能重载功能开发中,暂不启用\nimport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\nimport { rpx2pxPlugin } from \"./postcss-rpx2px\";\nimport process from \"node:process\";\nimport type { Plugin } from \"vite\";\n\nexport interface DevToolsOptions {\n /**\n * 是否为 Taro 项目\n * - true: 启用 Taro 相关插件(taroStyleAdapterPlugin、rpx2pxPlugin)\n * - false: 禁用 Taro 相关插件\n * - undefined: 自动检测(通过 process.env.TARO_ENV 判断,默认为 false)\n */\n isTaro?: boolean;\n\n /**\n * Taro style adapter options\n * Controls H5 responsive scaling to match mini-program rpx behavior\n * 仅在 isTaro 为 true 时生效\n */\n styleAdapter?: TaroStyleAdapterOptions;\n\n /**\n * 是否启用 JSX Source Tagger(通过 Symbol 标记元素源码位置)\n * 默认:开发模式启用\n */\n jsxSourceTagger?: boolean;\n\n /**\n * 是否启用 Tailwind Config 同步(生成 JSON 文件)\n * 默认:开发模式启用\n */\n tailwindConfigSync?: boolean;\n\n /**\n * Tailwind 配置文件路径\n * 默认:./tailwind.config.ts\n */\n tailwindConfigPath?: string;\n}\n\n/**\n * 开发工具插件集合,简化调用,vite.config.ts 直接 devTools() 即可\n *\n * @param options 配置项\n * @param options.isTaro 是否为 Taro 项目(默认根据 TARO_ENV 自动判断)\n * @param options.styleAdapter Taro H5 样式适配配置,designWidth 应与 Taro config 一致\n * @returns Plugin[] Vite 插件数组\n *\n * @example\n * ```ts\n * // Taro 项目 - config/dev.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [devTools({ isTaro: true })]\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // React 项目 - vite.config.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * plugins: [devTools()] // isTaro 默认为 false\n * }\n * ```\n */\nexport default function devTools(options: DevToolsOptions = {}): Plugin[] {\n // 判断是否为 Taro 项目\n // 优先使用用户显式配置,否则通过环境变量判断\n const isTaro = options.isTaro ?? process.env.TARO_ENV === \"h5\";\n\n const plugins: Plugin[] = [\n // componentIdPlugin(), // 暂不启用\n editorBridgePlugin(),\n routesExposePlugin(),\n // smartReloadPlugin() // 智能重载:拦截 full-reload,静默等待重连\n ];\n\n // JSX Source Tagger - 默认开发模式启用\n if (options.jsxSourceTagger !== false) {\n plugins.push(jsxSourceTaggerPlugin());\n }\n\n // Tailwind Config Sync - 默认开发模式启用\n if (options.tailwindConfigSync !== false) {\n plugins.push(\n tailwindConfigSyncPlugin({\n configPath: options.tailwindConfigPath,\n })\n );\n }\n\n // 仅在 Taro 项目中添加 Taro 相关插件\n if (isTaro) {\n // Taro H5 样式适配(运行时)\n plugins.unshift(taroStyleAdapterPlugin(options.styleAdapter));\n\n // H5 开发模式下添加 rpx2px PostCSS 插件(编译时)\n plugins.unshift({\n name: \"dev-postcss-rpx2px-plugin\",\n apply: \"serve\",\n config(config) {\n if (typeof config.css?.postcss === \"object\") {\n // 在最前面插入,确保在 pxtransform 之前执行\n config.css?.postcss.plugins?.unshift(rpx2pxPlugin());\n }\n },\n });\n }\n\n // process.env.WORKSPACE_GIT_REPO 有这个表示是在 sandbox 里面运行,启用浏览器日志插件\n if (process.env.WORKSPACE_GIT_REPO) {\n plugins.push(browserLogsPlugin());\n }\n\n return plugins;\n}\n\nexport {\n editorBridgePlugin,\n routesExposePlugin,\n // smartReloadPlugin\n};\n\n// Export Taro environment injection helpers\nexport { injectTaroEnv, injectAmasterEnv } from \"./taro-env-inject\";\n\n// Export Taro style adapter plugin and its types\nexport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\n\n// Export PostCSS rpx2px plugin for H5 mode\nexport { rpx2pxPlugin, type Rpx2pxPluginOptions } from \"./postcss-rpx2px\";\n\n// Export tagger and tailwind config sync plugins\nexport { jsxSourceTaggerPlugin } from \"./tagger\";\nexport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n"]}
1
+ {"version":3,"sources":["../src/editor-bridge.ts","../src/routes-expose.ts","../src/browser-logs.ts","../src/tagger.ts","../src/tailwind-config-sync.ts","../src/taro-style-adapter.ts","../src/postcss-rpx2px.ts","../src/taro-env-inject.ts","../src/index.ts"],"names":["clickHandlerScript","getBridgeScriptContent","sessionKey","editorBridgePlugin","isDev","config","html","bridgeScript","scriptsToInject","routesExposePlugin","options","routesPath","code","id","browserLogsPlugin","logFilePath","injectedScript","workspaceDir","process","path","dir","fs","devServer","req","res","next","origin","body","chunk","logDir","error","devRuntimeCode","jsxSourceTaggerPlugin","projectRoot","importer","tailwindConfigSyncPlugin","cachedConfig","configPath","VIRTUAL_MODULE_ID","RESOLVED_VIRTUAL_MODULE_ID","findConfigFile","configFile","jsConfig","tsConfig","generateConfig","tailwindInputFile","sourceCode","result","O","userConfig","Buffer","resolveConfig","resolvedConfig","server","file","mod","taroStyleAdapterPlugin","designWidth","maxWidth","baseFontSize","minRootSize","maxRootSize","flexibleScript","rpx2pxPlugin","ratio","decl","_match","num","pxValue","injectTaroEnv","additional","autoInjectTaroApp","autoInjectVite","constants","varsToInject","key","varName","value","injectAmasterEnv","devTools","isTaro","plugins"],"mappings":"2yBAEA,IAAMA,CAAAA,CAAqB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CAAA,CAuB3B,SAASC,CAAAA,CAAuBC,CAAAA,CAAoB,CAClD,OAAO,CAAA;AAAA;AAAA;AAAA,uBAAA,EAGgBA,CAAU,CAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CA+CnC,CAMO,SAASC,CAAAA,EAA6B,CAC3C,IAAIC,CAAAA,CAAQ,KAAA,CAEZ,OAAO,CACL,IAAA,CAAM,2BAAA,CAEN,eAAeC,CAAAA,CAAQ,CACrBD,CAAAA,CAAQC,CAAAA,CAAO,OAAA,GAAY,QAC7B,EAEA,kBAAA,CAAmBC,CAAAA,CAAM,CACvB,GAAI,CAACF,CAAAA,CAAO,OAAOE,CAAAA,CAEnB,OAAA,CAAQ,GAAA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YzB,CAAAA,CAAQ,kBACtB,CAAC,CACH,CAAA,CAIEsE,CAAAA,GAEFC,CAAAA,CAAQ,OAAA,CAAQzB,CAAAA,CAAuB9C,CAAAA,CAAQ,YAAY,CAAC,EAG5DuE,CAAAA,CAAQ,OAAA,CAAQ,CACd,IAAA,CAAM,2BAAA,CACN,KAAA,CAAO,OAAA,CACP,MAAA,CAAO5E,CAAAA,CAAQ,CACT,OAAOA,CAAAA,CAAO,GAAA,EAAK,OAAA,EAAY,QAAA,EAEjCA,CAAAA,CAAO,KAAK,OAAA,CAAQ,OAAA,EAAS,OAAA,CAAQ0D,CAAAA,EAAc,EAEvD,CACF,CAAC,CAAA,CAAA,CAIC7C,kBAAAA,CAAQ,GAAA,CAAI,kBAAA,EACd+D,CAAAA,CAAQ,IAAA,CAAKnE,CAAAA,EAAmB,EAG3BmE,CACT","file":"index.cjs","sourcesContent":["import type { Plugin } from \"vite\";\n\nconst clickHandlerScript = `<script>\ndocument.addEventListener(\"click\", (e) => {\n const element = e.target;\n const noJumpOut = document.body.classList.contains(\"forbid-jump-out\")\n if (element.hasAttribute(\"data-link-href\") && !noJumpOut) {\n const href = element.getAttribute(\"data-link-href\");\n const target = element.getAttribute(\"data-link-target\");\n if (href) {\n if (target === \"_blank\") {\n window.open(href, \"_blank\");\n } else {\n window.location.href = href;\n }\n }\n } else if(noJumpOut && element.tagName === \"A\") {\n e.preventDefault();\n }\n});\n</script>`;\n\n/**\n * Generate bridge script content with environment variables\n */\nfunction getBridgeScriptContent(sessionKey: string) {\n return `<script type=\"module\">\n(function() {\n const SOURCE_KEY = Symbol.for(\"__jsxSource__\");\n const SESSION_KEY = \"${sessionKey}\";\n\n // Expose minimal API for external bridge script\n window.__AMASTER_BRIDGE__ = {\n getSourceInfo: (element) => element?.[SOURCE_KEY],\n getSourceMap: () => window.sourceElementMap,\n postToParent: (type, data) => {\n window.parent.postMessage({ type, data, key: SESSION_KEY }, \"*\");\n },\n isDev: true,\n };\n\n // Listen for bridge script URL from platform\n window.addEventListener(\"message\", (event) => {\n const { type, data, key } = event.data;\n \n if (key !== SESSION_KEY) {\n console.warn(\"[Bridge] Invalid session key\");\n return;\n }\n \n if (type === \"amaster.loadBridge\" && data?.scriptContent) {\n console.log(\"[Bridge] Loading bridge from inline script\");\n \n // Create blob URL from script content\n const blob = new Blob([data.scriptContent], { type: 'application/javascript' });\n const blobUrl = URL.createObjectURL(blob);\n \n const script = document.createElement(\"script\");\n script.src = blobUrl;\n script.onload = () => {\n console.log(\"[Bridge] External script loaded\");\n URL.revokeObjectURL(blobUrl);\n };\n script.onerror = () => {\n console.error(\"[Bridge] Failed to load external script\");\n URL.revokeObjectURL(blobUrl);\n };\n document.head.appendChild(script);\n }\n });\n\n window.addEventListener(\"load\", () => {\n window.__AMASTER_BRIDGE__?.postToParent(\"amaster.bridge.initialized\", {});\n });\n})();\n</script>`;\n}\n\n/**\n * Vite plugin: Inject editor bridge script\n * Injects minimal bridge that loads external script from platform\n */\nexport function editorBridgePlugin(): Plugin {\n let isDev = false;\n\n return {\n name: \"vite-plugin-editor-bridge\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transformIndexHtml(html) {\n if (!isDev) return html;\n\n console.log(\"[editorBridgePlugin] Injecting bridge script\");\n const sessionKey = process.env.VITE_AMASTER_KEY || \"\";\n const bridgeScript = getBridgeScriptContent(sessionKey);\n const scriptsToInject = `${clickHandlerScript}${bridgeScript}</body>`;\n return html.replace(\"</body>\", scriptsToInject);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Vite plugin: Expose routes to window.__APP_ROUTES__\n * Only enabled in development mode\n */\nexport function routesExposePlugin(options?: { routesFilePath?: string }): Plugin {\n let isDev = false;\n const routesPath = options?.routesFilePath || \"src/routes.tsx\";\n\n return {\n name: \"vite-plugin-routes-expose\",\n enforce: \"post\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transform(code: string, id: string) {\n if (!isDev) {\n return null;\n }\n\n if (!id.endsWith(routesPath)) {\n return null;\n }\n\n try {\n if (code.includes(\"window.__APP_ROUTES__\")) {\n return null;\n }\n\n const transformedCode = `${code}\n\n// Development mode: Expose routes to window.__APP_ROUTES__\nif (typeof window !== 'undefined') {\n window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];\n}\n`;\n\n return {\n code: transformedCode,\n map: null,\n };\n } catch {\n return null;\n }\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport { Buffer } from \"node:buffer\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\n/**\n * Browser logs collection plugin\n * Injects script into HTML head to collect console logs and network requests\n * Logs are written directly to browser.log file (same level as index.html)\n */\nexport function browserLogsPlugin(): Plugin {\n let logFilePath = \"\";\n\n // Script to inject into browser\n const injectedScript = `\n<script>\n(function() {\n 'use strict';\n \n // Log API path (provided by Vite dev server)\n var LOG_API_PATH = '/__browser__';\n \n // Write queue to ensure sequential writes\n var writeQueue = [];\n var isWriting = false;\n \n // Process write queue to ensure sequential writes\n function processWriteQueue() {\n if (isWriting || writeQueue.length === 0) return;\n \n isWriting = true;\n var entry = writeQueue.shift();\n var logText = JSON.stringify(entry);\n \n fetch(LOG_API_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: logText\n })\n .then(function(response) {\n isWriting = false;\n if (!response.ok) {\n console.warn('[BrowserLogs] Failed to write log:', response.status);\n }\n // Continue processing next item in queue\n processWriteQueue();\n })\n .catch(function(error) {\n console.warn('[BrowserLogs] Failed to write log:', error.message);\n // On failure, put log back to queue head for retry\n writeQueue.unshift(entry);\n isWriting = false;\n // Retry after delay\n setTimeout(processWriteQueue, 1000);\n });\n }\n \n // Limit headers object size\n function truncateHeaders(headers) {\n if (!headers) return headers;\n var jsonStr = JSON.stringify(headers);\n if (jsonStr.length <= MAX_HEADER_SIZE) return headers;\n return '[Headers truncated, size: ' + jsonStr.length + ']';\n }\n \n // Truncate oversized log entries\n function truncateLogEntry(entry) {\n var jsonStr = JSON.stringify(entry);\n if (jsonStr.length <= MAX_LOG_ENTRY_SIZE) {\n return entry;\n }\n \n // If oversized, progressively truncate non-critical fields\n var truncated = Object.assign({}, entry);\n \n // 1. Truncate response body first\n if (truncated.responseBody && typeof truncated.responseBody === 'string') {\n truncated.responseBody = truncated.responseBody.substring(0, 500) + '... [truncated]';\n }\n \n // 2. Truncate request body\n if (truncated.requestBody && typeof truncated.requestBody === 'string') {\n truncated.requestBody = truncated.requestBody.substring(0, 500) + '... [truncated]';\n }\n \n // 3. Truncate message\n if (truncated.message && typeof truncated.message === 'string' && truncated.message.length > 1000) {\n truncated.message = truncated.message.substring(0, 1000) + '... [truncated]';\n }\n \n // 4. Truncate stack\n if (truncated.stack && Array.isArray(truncated.stack) && truncated.stack.length > 3) {\n truncated.stack = truncated.stack.slice(0, 3);\n }\n \n // Add truncation marker\n truncated._truncated = true;\n truncated._originalSize = jsonStr.length;\n \n return truncated;\n }\n \n // Add log and send immediately (ensure order)\n function addLog(entry) {\n var truncatedEntry = truncateLogEntry(entry);\n writeQueue.push(truncatedEntry);\n processWriteQueue();\n }\n \n // ============================================\n // Console log collection\n // ============================================\n var originalConsole = {\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error,\n debug: console.debug\n };\n \n function getStackTrace() {\n var stack = new Error().stack || '';\n var lines = stack.split('\\\\n').slice(3);\n // Limit stack lines\n return lines.slice(0, MAX_STACK_LINES).map(function(line) { return line.trim(); });\n }\n \n function formatMessage(args) {\n return Array.from(args).map(function(arg) {\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg);\n } catch (e) {\n return String(arg);\n }\n }\n return String(arg);\n }).join(' ');\n }\n \n function createLogEntry(level, args) {\n return {\n type: 'console',\n timestamp: new Date().toISOString(),\n level: level,\n message: formatMessage(args),\n stack: getStackTrace()\n };\n }\n \n // Check if message should be filtered (contains [vite] text)\n function shouldFilterConsoleLog(args) {\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n if (typeof arg === 'string' && arg.indexOf('[vite]') !== -1) {\n return true;\n }\n }\n return false;\n }\n \n function wrapConsoleMethod(method, level) {\n return function() {\n var args = arguments;\n // Filter out logs containing [vite]\n if (shouldFilterConsoleLog(args)) {\n return originalConsole[method].apply(console, args);\n }\n var entry = createLogEntry(level, args);\n addLog(entry);\n return originalConsole[method].apply(console, args);\n };\n }\n \n console.log = wrapConsoleMethod('log', 'log');\n console.info = wrapConsoleMethod('info', 'info');\n console.warn = wrapConsoleMethod('warn', 'warn');\n console.error = wrapConsoleMethod('error', 'error');\n console.debug = wrapConsoleMethod('debug', 'debug');\n \n // ============================================\n // Network request collection (exclude SSE and log API requests)\n // ============================================\n \n var MAX_BODY_SIZE = 2000;\n var MAX_LOG_ENTRY_SIZE = 3000; // Max single log entry length\n var MAX_HEADER_SIZE = 500; // Max single header object length\n var MAX_STACK_LINES = 5; // Max stack lines to keep\n const FILTERED_URLS = ['/__browser__', '/builtin']; // Filter out log API and Vite built-in requests\n \n function isSSERequest(url, headers) {\n var sseUrlPatterns = ['/events', '/sse', '/stream', 'text/event-stream'];\n var urlStr = String(url).toLowerCase();\n for (var i = 0; i < sseUrlPatterns.length; i++) {\n if (urlStr.indexOf(sseUrlPatterns[i]) !== -1) {\n return true;\n }\n }\n \n if (headers) {\n if (typeof headers.get === 'function') {\n var accept = headers.get('Accept') || headers.get('accept');\n if (accept && accept.indexOf('text/event-stream') !== -1) {\n return true;\n }\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n if (key.toLowerCase() === 'accept' && headers[key].indexOf('text/event-stream') !== -1) {\n return true;\n }\n }\n }\n }\n \n return false;\n }\n \n function shouldFilterRequest(url) {\n return FILTERED_URLS.some(function(filteredUrl) {\n return String(url).indexOf(filteredUrl) !== -1;\n });\n }\n \n function formatRequestBody(body) {\n if (!body) return null;\n \n try {\n if (typeof body === 'string') {\n return body.substring(0, MAX_BODY_SIZE);\n }\n if (body instanceof FormData) {\n var formDataObj = {};\n body.forEach(function(value, key) {\n if (value instanceof File) {\n formDataObj[key] = '[File: ' + value.name + ', size: ' + value.size + ']';\n } else {\n formDataObj[key] = String(value).substring(0, 1000);\n }\n });\n return JSON.stringify(formDataObj);\n }\n if (body instanceof Blob) {\n return '[Blob: size=' + body.size + ', type=' + body.type + ']';\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return '[Binary: size=' + body.byteLength + ']';\n }\n if (body instanceof URLSearchParams) {\n return body.toString().substring(0, MAX_BODY_SIZE);\n }\n return String(body).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading body: ' + e.message + ']';\n }\n }\n \n function formatResponseBody(response, responseType) {\n if (!response) return null;\n \n try {\n if (responseType === '' || responseType === 'text') {\n return String(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'json') {\n return JSON.stringify(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'document') {\n return '[Document]';\n }\n if (responseType === 'blob') {\n return '[Blob: size=' + response.size + ']';\n }\n if (responseType === 'arraybuffer') {\n return '[ArrayBuffer: size=' + response.byteLength + ']';\n }\n return String(response).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading response: ' + e.message + ']';\n }\n }\n \n // Intercept XMLHttpRequest\n var originalXHROpen = XMLHttpRequest.prototype.open;\n var originalXHRSend = XMLHttpRequest.prototype.send;\n var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;\n \n XMLHttpRequest.prototype.open = function(method, url, async, user, password) {\n this.__requestInfo__ = {\n method: method,\n url: url,\n startTime: null,\n headers: {}\n };\n return originalXHROpen.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.setRequestHeader = function(name, value) {\n if (this.__requestInfo__ && this.__requestInfo__.headers) {\n this.__requestInfo__.headers[name] = value;\n }\n return originalXHRSetRequestHeader.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.send = function(body) {\n var xhr = this;\n var requestInfo = xhr.__requestInfo__;\n \n if (requestInfo) {\n // Skip SSE requests and filtered requests\n if (isSSERequest(requestInfo.url, requestInfo.headers) || shouldFilterRequest(requestInfo.url)) {\n return originalXHRSend.apply(this, arguments);\n }\n \n requestInfo.startTime = Date.now();\n requestInfo.requestBody = formatRequestBody(body);\n \n xhr.addEventListener('loadend', function() {\n var contentType = xhr.getResponseHeader('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return;\n }\n \n var responseHeaders = {};\n var allHeaders = xhr.getAllResponseHeaders();\n if (allHeaders) {\n allHeaders.split('\\\\r\\\\n').forEach(function(line) {\n var parts = line.split(': ');\n if (parts.length === 2) {\n responseHeaders[parts[0]] = parts[1];\n }\n });\n }\n \n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'xhr',\n method: requestInfo.method,\n url: requestInfo.url,\n status: xhr.status,\n statusText: xhr.statusText,\n duration: Date.now() - requestInfo.startTime,\n requestHeaders: truncateHeaders(requestInfo.headers),\n requestBody: requestInfo.requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseType: xhr.responseType,\n responseBody: formatResponseBody(xhr.response, xhr.responseType),\n responseSize: xhr.response ? (typeof xhr.response === 'string' ? xhr.response.length : (xhr.response.byteLength || xhr.response.size || null)) : null\n };\n \n addLog(entry);\n });\n }\n \n return originalXHRSend.apply(this, arguments);\n };\n \n // Intercept Fetch API\n var originalFetch = window.fetch;\n \n function headersToObject(headers) {\n var obj = {};\n if (!headers) return obj;\n \n if (typeof headers.forEach === 'function') {\n headers.forEach(function(value, key) {\n obj[key] = value;\n });\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n obj[key] = headers[key];\n }\n }\n return obj;\n }\n \n window.fetch = function(input, init) {\n var startTime = Date.now();\n var method = (init && init.method) || 'GET';\n var url = typeof input === 'string' ? input : input.url;\n var headers = init && init.headers;\n \n // Skip SSE requests and filtered requests\n if (isSSERequest(url, headers) || shouldFilterRequest(url)) {\n return originalFetch.apply(this, arguments);\n }\n \n var requestHeaders = headersToObject(headers);\n var requestBody = formatRequestBody(init && init.body);\n \n return originalFetch.apply(this, arguments)\n .then(function(response) {\n var contentType = response.headers.get('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return response;\n }\n \n var clonedResponse = response.clone();\n var responseHeaders = headersToObject(response.headers);\n \n clonedResponse.text().then(function(bodyText) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: bodyText ? bodyText.substring(0, MAX_BODY_SIZE) : null,\n responseSize: bodyText ? bodyText.length : null,\n ok: response.ok\n };\n \n addLog(entry);\n }).catch(function(e) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: '[Unable to read: ' + e.message + ']',\n responseSize: null,\n ok: response.ok\n };\n \n addLog(entry);\n });\n \n return response;\n })\n .catch(function(error) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: 0,\n statusText: 'Network Error',\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: null,\n responseBody: null,\n error: error.message\n };\n \n addLog(entry);\n throw error;\n });\n };\n \n // ============================================\n // Global error capture\n // ============================================\n window.addEventListener('error', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: event.message,\n stack: event.error ? event.error.stack : 'at ' + event.filename + ':' + event.lineno + ':' + event.colno\n };\n addLog(entry);\n });\n \n // ============================================\n // Vite deps 504 error capture using PerformanceObserver\n // Only captures 504 errors for node_modules/.vite resources (pre-bundled dependencies)\n // ============================================\n var reportedUrls = {}; // Track reported URLs to avoid duplicates\n \n if (typeof PerformanceObserver !== 'undefined') {\n var perfObserver = new PerformanceObserver(function(list) {\n var entries = list.getEntries();\n for (var i = 0; i < entries.length; i++) {\n var perfEntry = entries[i];\n // Only check script resources\n if (perfEntry.initiatorType !== 'script') {\n continue;\n }\n \n var resourceUrl = perfEntry.name || '';\n // Only report errors for node_modules/.vite resources\n if (resourceUrl.indexOf('node_modules/.vite') === -1 && resourceUrl.indexOf('/node_modules/.vite') === -1) {\n continue;\n }\n \n // Check if response status is 504 (Gateway Timeout)\n // responseStatus is available in Resource Timing Level 2\n var status = perfEntry.responseStatus;\n if (status === 504) {\n // Avoid duplicate reports\n if (reportedUrls[resourceUrl]) {\n continue;\n }\n reportedUrls[resourceUrl] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: resourceUrl,\n status: 504,\n message: 'Vite pre-bundled dependency returned 504 Gateway Timeout: ' + resourceUrl,\n duration: perfEntry.duration,\n transferSize: perfEntry.transferSize\n };\n addLog(entry);\n }\n }\n });\n \n try {\n perfObserver.observe({ type: 'resource', buffered: true });\n } catch (e) {\n // Fallback for browsers that don't support the options\n try {\n perfObserver.observe({ entryTypes: ['resource'] });\n } catch (e2) {\n originalConsole.warn('[BrowserLogs] PerformanceObserver not supported:', e2.message);\n }\n }\n }\n \n // ============================================\n // Script load error capture (for 504 and other network errors)\n // This captures errors that PerformanceObserver might miss\n // ============================================\n \n // Use MutationObserver to watch for dynamically added script tags\n function attachScriptErrorHandler(script) {\n if (script.__errorHandlerAttached__) return;\n script.__errorHandlerAttached__ = true;\n \n script.addEventListener('error', function(event) {\n var src = script.src || '';\n \n // Only report errors for node_modules/.vite resources\n if (src.indexOf('node_modules/.vite') === -1 && src.indexOf('/node_modules/.vite') === -1) {\n return;\n }\n \n // Avoid duplicate reports\n if (reportedUrls[src]) {\n return;\n }\n reportedUrls[src] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: src,\n status: 'load-error',\n message: 'Vite pre-bundled dependency failed to load (possibly 504 Gateway Timeout): ' + src,\n errorType: event.type\n };\n addLog(entry);\n });\n }\n \n // Attach error handlers to existing scripts\n var existingScripts = document.querySelectorAll('script[src]');\n for (var i = 0; i < existingScripts.length; i++) {\n attachScriptErrorHandler(existingScripts[i]);\n }\n \n // Watch for dynamically added scripts\n if (typeof MutationObserver !== 'undefined') {\n var scriptObserver = new MutationObserver(function(mutations) {\n for (var i = 0; i < mutations.length; i++) {\n var mutation = mutations[i];\n for (var j = 0; j < mutation.addedNodes.length; j++) {\n var node = mutation.addedNodes[j];\n if (node.nodeName === 'SCRIPT' && node.src) {\n attachScriptErrorHandler(node);\n }\n // Also check child nodes\n if (node.querySelectorAll) {\n var scripts = node.querySelectorAll('script[src]');\n for (var k = 0; k < scripts.length; k++) {\n attachScriptErrorHandler(scripts[k]);\n }\n }\n }\n }\n });\n \n scriptObserver.observe(document.documentElement, {\n childList: true,\n subtree: true\n });\n }\n \n // Also intercept document.createElement to catch scripts before they're added to DOM\n var originalCreateElement = document.createElement.bind(document);\n document.createElement = function(tagName) {\n var element = originalCreateElement(tagName);\n if (tagName.toLowerCase() === 'script') {\n // Use a setter to catch when src is set\n var originalSrc = '';\n Object.defineProperty(element, '__originalSrc__', {\n get: function() { return originalSrc; },\n set: function(val) { originalSrc = val; }\n });\n \n // Defer attaching error handler until src is set\n var srcDescriptor = Object.getOwnPropertyDescriptor(HTMLScriptElement.prototype, 'src');\n if (srcDescriptor && srcDescriptor.set) {\n var originalSrcSetter = srcDescriptor.set;\n Object.defineProperty(element, 'src', {\n get: function() {\n return srcDescriptor.get ? srcDescriptor.get.call(this) : this.getAttribute('src');\n },\n set: function(value) {\n if (originalSrcSetter) {\n originalSrcSetter.call(this, value);\n } else {\n this.setAttribute('src', value);\n }\n attachScriptErrorHandler(this);\n },\n configurable: true\n });\n }\n }\n return element;\n };\n \n window.addEventListener('unhandledrejection', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),\n stack: event.reason && event.reason.stack ? event.reason.stack : ''\n };\n addLog(entry);\n });\n \n // ============================================\n // Send remaining logs on page unload\n // ============================================\n window.addEventListener('beforeunload', function() {\n if (writeQueue.length > 0) {\n // Use sendBeacon to ensure logs are sent\n writeQueue.forEach(function(entry) {\n navigator.sendBeacon(LOG_API_PATH, JSON.stringify(entry));\n });\n writeQueue = [];\n }\n });\n \n // ============================================\n // Provide manual flush method\n // ============================================\n window.__flushBrowserLogs__ = function() {\n return new Promise(function(resolve) {\n // Wait for queue to finish processing\n function checkQueue() {\n if (writeQueue.length === 0 && !isWriting) {\n resolve();\n } else {\n setTimeout(checkQueue, 100);\n }\n }\n checkQueue();\n });\n };\n \n // Provide method to get queue status\n window.__getBrowserLogsStatus__ = function() {\n return {\n queueLength: writeQueue.length,\n isWriting: isWriting\n };\n };\n \n originalConsole.log('[BrowserLogs] Log collection started');\n})();\n</script>`;\n\n return {\n name: \"vite-plugin-browser-logs\",\n\n configResolved(config) {\n // Determine log file path: use WORKSPACE_DIR env var (set by PM2/Docker),\n // or find the nearest directory containing package.json from config.root,\n // to ensure browser.log is always at the workspace root level.\n const workspaceDir = process.env.WORKSPACE_DIR;\n if (workspaceDir) {\n logFilePath = path.join(workspaceDir, \"browser.log\");\n } else {\n // Fallback: walk up from config.root to find directory with package.json\n let dir = config.root || process.cwd();\n while (dir !== path.dirname(dir)) {\n if (fs.existsSync(path.join(dir, \"package.json\"))) {\n break;\n }\n dir = path.dirname(dir);\n }\n logFilePath = path.join(dir, \"browser.log\");\n }\n },\n\n configureServer(devServer) {\n // Add log write API\n devServer.middlewares.use((req, res, next) => {\n if (req.url === \"/__browser__\" && req.method === \"POST\") {\n // Get request origin, dynamically set CORS headers to avoid protocol mismatch\n const origin = req.headers.origin || \"*\";\n\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n try {\n // Ensure log directory exists\n const logDir = path.dirname(logFilePath);\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n // Append to log file\n fs.appendFileSync(logFilePath, `${body}\\n`, \"utf-8\");\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: true }));\n } catch (error) {\n console.error(\"[BrowserLogs] Write error:\", error);\n res.writeHead(500, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: false, error: String(error) }));\n }\n });\n } else if (req.url === \"/__browser__\" && req.method === \"OPTIONS\") {\n // Handle CORS preflight request\n const origin = req.headers.origin || \"*\";\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n res.end();\n } else if (req.url === \"/__browser__\") {\n const origin = req.headers.origin || \"*\";\n res.writeHead(405, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n });\n res.end(JSON.stringify({ error: \"Method not allowed\" }));\n } else {\n next();\n }\n });\n\n console.log(\"[BrowserLogs] Logs will be written to:\", logFilePath);\n },\n\n transformIndexHtml(html) {\n // Insert script after <head> tag to ensure earliest execution\n return html.replace(/<head([^>]*)>/i, `<head$1>${injectedScript}`);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Runtime code that will be injected to replace react/jsx-dev-runtime\n * This code tags DOM elements with source information using refs\n */\nconst devRuntimeCode = `\nimport * as React from \"react\";\nimport * as ReactJSXDevRuntime from \"react/jsx-dev-runtime\";\n\nconst _jsxDEV = ReactJSXDevRuntime.jsxDEV;\nexport const Fragment = ReactJSXDevRuntime.Fragment;\n\nconst SOURCE_KEY = Symbol.for(\"__jsxSource__\");\nconst PROJECT_ROOT = \"\";\n\nconst cleanFileName = (fileName) => {\n if (!fileName) return \"\";\n // Remove project root prefix to get relative path\n if (PROJECT_ROOT && fileName.startsWith(PROJECT_ROOT)) {\n const relative = fileName.slice(PROJECT_ROOT.length);\n return relative.startsWith(\"/\") ? relative.slice(1) : relative;\n }\n return fileName;\n};\n\n// Global map to track elements by source location\nconst sourceElementMap = new Map();\nwindow.sourceElementMap = sourceElementMap;\n\nfunction getSourceKey(sourceInfo) {\n return \\`\\${cleanFileName(sourceInfo.fileName)}:\\${sourceInfo.lineNumber}:\\${sourceInfo.columnNumber}\\`;\n}\n\nfunction unregisterElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n const refs = sourceElementMap.get(key);\n if (refs) {\n for (const ref of refs) {\n if (ref.deref() === node) {\n refs.delete(ref);\n break;\n }\n }\n if (refs.size === 0) {\n sourceElementMap.delete(key);\n }\n }\n}\n\nfunction registerElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n if (!sourceElementMap.has(key)) {\n sourceElementMap.set(key, new Set());\n }\n sourceElementMap.get(key).add(new WeakRef(node));\n}\n\nfunction getTypeName(type) {\n if (typeof type === \"string\") return type;\n if (typeof type === \"function\") return type.displayName || type.name || \"Unknown\";\n if (typeof type === \"object\" && type !== null) {\n return type.displayName || type.render?.displayName || type.render?.name || \"Unknown\";\n }\n return \"Unknown\";\n}\n\nexport function jsxDEV(type, props, key, isStatic, source, self) {\n // For custom components, tag their rendered output\n if (source?.fileName && typeof type !== \"string\" && type !== Fragment) {\n const typeName = getTypeName(type);\n const jsxSourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: typeName,\n };\n\n const originalRef = props?.ref;\n \n // Check if component can safely receive refs\n // - forwardRef components have $$typeof symbol\n // - Class components have prototype.isReactComponent\n // - If there's already a ref, the component expects it\n const isForwardRef = type.$$typeof === Symbol.for('react.forward_ref');\n const isClassComponent = typeof type === 'function' && type.prototype?.isReactComponent;\n const hasExistingRef = originalRef !== undefined;\n \n const canReceiveRef = isForwardRef || isClassComponent || hasExistingRef;\n \n if (canReceiveRef) {\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n if (!node[SOURCE_KEY]) {\n node[SOURCE_KEY] = jsxSourceInfo;\n registerElement(node, jsxSourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n }\n\n // For host elements (div, span, etc.), tag with source info\n if (source?.fileName && typeof type === \"string\") {\n const sourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: type,\n };\n\n const originalRef = props?.ref;\n\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n const existingSource = node[SOURCE_KEY];\n if (existingSource) {\n if (getSourceKey(existingSource) !== getSourceKey(sourceInfo)) {\n unregisterElement(node, existingSource);\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n } else {\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n}\n`;\n\n/**\n * Vite plugin: JSX Source Tagger\n * Intercepts react/jsx-dev-runtime to add source information to DOM elements\n * Only enabled in development mode\n */\nexport function jsxSourceTaggerPlugin(): Plugin {\n let isDev = false;\n let projectRoot = \"\";\n\n return {\n name: \"vite-plugin-jsx-source-tagger\",\n enforce: \"pre\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n projectRoot = config.root;\n },\n\n resolveId(id, importer) {\n if (!isDev) return null;\n\n // Intercept react/jsx-dev-runtime imports\n if (id === \"react/jsx-dev-runtime\" && !importer?.includes(\"\\0jsx-source\")) {\n return \"\\0jsx-source/jsx-dev-runtime\";\n }\n return null;\n },\n\n load(id) {\n if (!isDev) return null;\n\n // Return our custom runtime code with injected projectRoot\n if (id === \"\\0jsx-source/jsx-dev-runtime\") {\n return devRuntimeCode.replace(\n 'const PROJECT_ROOT = \"\";',\n `const PROJECT_ROOT = ${JSON.stringify(projectRoot)};`\n );\n }\n return null;\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport * as esbuild from \"esbuild\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Vite plugin: Tailwind Config Sync\n * Generates a JSON file from tailwind.config.ts for runtime access\n * Only enabled in development mode\n */\nexport function tailwindConfigSyncPlugin(options?: { configPath?: string }): Plugin {\n let projectRoot = \"\";\n let isDev = false;\n let cachedConfig: Record<string, unknown> | null = null;\n\n const configPath = options?.configPath || \"./tailwind.config.ts\";\n const VIRTUAL_MODULE_ID = \"@amaster/tailwind-config\";\n const RESOLVED_VIRTUAL_MODULE_ID = \"\\0\" + VIRTUAL_MODULE_ID;\n\n const findConfigFile = async (): Promise<string | null> => {\n const configFile = path.resolve(projectRoot, configPath);\n\n try {\n await fs.access(configFile);\n return configFile;\n } catch {\n // If specified config doesn't exist, try alternative extensions\n if (configPath.endsWith(\".ts\")) {\n const jsConfig = configFile.replace(/\\.ts$/, \".js\");\n try {\n await fs.access(jsConfig);\n return jsConfig;\n } catch {\n return null;\n }\n } else if (configPath.endsWith(\".js\")) {\n const tsConfig = configFile.replace(/\\.js$/, \".ts\");\n try {\n await fs.access(tsConfig);\n return tsConfig;\n } catch {\n return null;\n }\n }\n return null;\n }\n };\n\n const generateConfig = async (): Promise<Record<string, unknown> | null> => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (!tailwindInputFile) return null;\n\n const sourceCode = await fs.readFile(tailwindInputFile, \"utf-8\");\n const result = await esbuild.transform(sourceCode, {\n loader: tailwindInputFile.endsWith(\".ts\") ? \"ts\" : \"js\",\n format: \"esm\",\n platform: \"node\",\n });\n\n const dataUrl = `data:text/javascript;base64,${Buffer.from(result.code).toString(\"base64\")}`;\n const userConfig = await import(dataUrl);\n\n if (!userConfig?.default) {\n throw new Error(\"Invalid Tailwind config structure\");\n }\n\n // Try to resolve with tailwindcss, fallback to raw config\n try {\n const resolveConfig = (await import(\"tailwindcss/resolveConfig.js\")).default;\n cachedConfig = resolveConfig(userConfig.default);\n } catch {\n cachedConfig = userConfig.default;\n }\n\n return cachedConfig;\n } catch {\n return null;\n }\n };\n\n return {\n name: \"vite-plugin-tailwind-config-sync\",\n\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n isDev = resolvedConfig.command === \"serve\";\n },\n\n async buildStart() {\n if (!isDev) return;\n await generateConfig();\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return RESOLVED_VIRTUAL_MODULE_ID;\n }\n },\n\n async load(id) {\n if (id === RESOLVED_VIRTUAL_MODULE_ID) {\n if (!cachedConfig) {\n await generateConfig();\n }\n\n // Generate code with HMR support\n const code = `\nlet config = ${JSON.stringify(cachedConfig)};\n\nlet _updateConfig;\nif (import.meta.hot) {\n // Accept self updates\n import.meta.hot.accept((newModule) => {\n if (newModule && _updateConfig) {\n _updateConfig(newModule.default);\n }\n });\n}\n\nexport default new Proxy(config, {\n get(target, prop) {\n if (prop === 'then') return undefined;\n if (prop === '__setUpdater') {\n return (fn) => { _updateConfig = fn; };\n }\n return target[prop];\n }\n});\n`;\n return code;\n }\n },\n\n configureServer(server) {\n if (!isDev) return;\n\n (async () => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (tailwindInputFile) {\n server.watcher.add(tailwindInputFile);\n }\n } catch {\n // Ignore errors\n }\n })();\n },\n\n async handleHotUpdate({ file, server }) {\n const tailwindInputFile = await findConfigFile();\n\n if (!tailwindInputFile || path.normalize(file) !== path.normalize(tailwindInputFile)) {\n return;\n }\n\n await generateConfig();\n\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n return [mod];\n }\n\n return [];\n },\n };\n}\n","import type { Plugin } from 'vite';\n\nexport interface TaroStyleAdapterOptions {\n /**\n * Design width for responsive scaling (default: 375)\n * Should match Taro config's designWidth\n */\n designWidth?: number;\n \n /**\n * Maximum viewport width to scale (default: 750)\n * Beyond this width, font-size stays fixed\n */\n maxWidth?: number;\n\n /**\n * Base font size in pixels (default: 12)\n * Should match Taro config's baseFontSize\n */\n baseFontSize?: number;\n\n /**\n * Minimum root font size in pixels (default: 12)\n * Should match Taro config's minRootSize\n */\n minRootSize?: number;\n\n /**\n * Maximum root font size in pixels (default: 24)\n * Should match Taro config's maxRootSize\n */\n maxRootSize?: number;\n}\n\n/**\n * Taro H5 样式适配插件\n * \n * 功能:\n * 1. 动态计算根字号,使 H5 的 rem 与小程序的 rpx 行为对齐\n * 2. 隐藏 Taro 页面容器的滚动条,用于编辑器 iframe 预览\n * \n * 原理:\n * - 小程序 rpx: 1rpx = 屏幕宽度 / 750\n * - H5 rem: Taro 把 rpx 转成 rem,基于 baseFontSize\n * - 本插件动态设置 html font-size,使 rem 的实际像素值与 rpx 对齐\n * \n * 注意:此插件会覆盖 Taro 默认注入的根字号脚本,配置需与 Taro pxtransform 保持一致\n * \n * @example\n * ```ts\n * // In Taro config/dev.ts\n * import { taroStyleAdapterPlugin } from '@amaster.ai/vite-plugins'\n * \n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [\n * taroStyleAdapterPlugin({ \n * designWidth: 375,\n * baseFontSize: 12,\n * minRootSize: 12,\n * maxRootSize: 24\n * })\n * ]\n * }\n * }\n * ```\n */\nexport function taroStyleAdapterPlugin(options: TaroStyleAdapterOptions = {}): Plugin {\n const { \n designWidth = 375, \n maxWidth = 750,\n baseFontSize = 12,\n minRootSize = 12,\n maxRootSize = 24\n } = options;\n \n return {\n name: 'vite-plugin-taro-style-adapter',\n apply: 'serve', // 仅在开发模式下生效\n transformIndexHtml(html) {\n // 动态根字号脚本\n // 公式:fontSize = (clientWidth / designWidth) * baseFontSize\n // 当 designWidth=375, baseFontSize=12 时:\n // - 375px 屏幕 → 12px (1rem = 12px)\n // - 750px 屏幕 → 24px (1rem = 24px)\n // 这样 rem 值在不同屏幕宽度下的视觉比例与小程序 rpx 一致\n const flexibleScript = `\n<script data-taro-flexible=\"true\">\n(function() {\n var designWidth = ${designWidth};\n var maxWidth = ${maxWidth};\n var baseFontSize = ${baseFontSize};\n var minRootSize = ${minRootSize};\n var maxRootSize = ${maxRootSize};\n \n function setRootFontSize() {\n var docEl = document.documentElement;\n var clientWidth = docEl.clientWidth;\n \n // 限制最大宽度\n if (clientWidth > maxWidth) {\n clientWidth = maxWidth;\n }\n \n // 计算根字号: (屏幕宽度 / 设计稿宽度) * 基准字号\n var fontSize = (clientWidth / designWidth) * baseFontSize;\n \n // 应用最小/最大限制\n if (fontSize < minRootSize) {\n fontSize = minRootSize;\n } else if (fontSize > maxRootSize) {\n fontSize = maxRootSize;\n }\n \n docEl.style.fontSize = fontSize + 'px';\n }\n \n setRootFontSize();\n \n // 监听窗口变化\n window.addEventListener('resize', setRootFontSize);\n window.addEventListener('orientationchange', setRootFontSize);\n \n // 页面显示时重新计算(解决某些浏览器的 bug)\n document.addEventListener('DOMContentLoaded', setRootFontSize);\n})();\n</script>\n`;\n\n // 滚动条隐藏样式 + Taro Image 组件修复\n const styles = `\n<style data-taro-adapter=\"true\">\n /* 仅 H5 生效:隐藏 Taro 页面容器滚动条,但仍可滚动 */\n .taro_page {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro_page::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /* 隐藏 Taro ScrollView 组件的滚动条 */\n .taro-scroll-view__scroll-y,\n .taro-scroll-view__scroll-x {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro-scroll-view__scroll-y::-webkit-scrollbar,\n .taro-scroll-view__scroll-x::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /*\n * 修复 Taro Image 组件在 H5 下的尺寸问题\n * \n * 问题:Taro Image 组件使用 aspectFit 模式时,内部 img 使用 max-width/max-height: 100%\n * 导致小尺寸图片(如 SVG 图标)无法按指定尺寸显示,只显示原始尺寸\n * \n * 解决:让 img 填满 taro-image-core 容器,由容器控制尺寸\n */\n taro-image-core img.taro-img__mode-aspectfit {\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n position: static;\n transform: none;\n object-fit: contain;\n }\n</style>\n`;\n \n // 在 </head> 之前插入脚本和样式\n return html.replace('</head>', `${flexibleScript}${styles}</head>`);\n }\n };\n}\n","/**\n * PostCSS 插件:H5 模式下将 rpx 预转换为 px\n *\n * 问题背景:\n * - Taro 的 pxtransform 在 H5 模式下会处理 rpx,但它把 rpx 值直接除以 rootValue\n * - 导致 96rpx 被转成 8rem(96/12),实际显示为 96px\n * - 而正确应该是:96rpx = 48px = 4rem = 48px\n *\n * 解决方案:\n * - 在 pxtransform 之前,先把 rpx 转成 px(rpx / 2)\n * - 然后 pxtransform 会正确地把 px 转成 rem(px / 12)\n *\n * 转换链路:96rpx → 48px → 4rem → 48px(正确)\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { rpx2pxPlugin } from '@amaster.ai/vite-plugins'\n * \n * // 在 postcss-config-loader-plugin 中使用\n * {\n * name: 'postcss-config-loader-plugin',\n * config(config) {\n * if (typeof config.css?.postcss === 'object') {\n * config.css?.postcss.plugins?.unshift(tailwindcss())\n * // H5 模式下添加 rpx2px 插件\n * if (process.env.TARO_ENV === 'h5') {\n * config.css?.postcss.plugins?.unshift(rpx2pxPlugin())\n * }\n * }\n * }\n * }\n * ```\n */\n\nexport interface Rpx2pxPluginOptions {\n /**\n * rpx 到 px 的转换比例(默认 2)\n * 即 1rpx = 1/ratio px\n * 默认值 2 表示 2rpx = 1px(基于 375 设计稿)\n */\n ratio?: number;\n}\n\ninterface PostCSSDeclaration {\n value: string;\n}\n\ninterface PostCSSPlugin {\n postcssPlugin: string;\n Declaration: (decl: PostCSSDeclaration) => void;\n}\n\ntype PostCSSPluginCreator = {\n (): PostCSSPlugin;\n postcss: boolean;\n};\n\nexport function rpx2pxPlugin(options: Rpx2pxPluginOptions = {}): PostCSSPlugin {\n const { ratio = 2 } = options;\n \n return {\n postcssPlugin: 'postcss-rpx2px',\n Declaration(decl: PostCSSDeclaration) {\n if (decl.value.includes('rpx')) {\n decl.value = decl.value.replace(/(-?\\d*\\.?\\d+)rpx/gi, (_match: string, num: string) => {\n const pxValue = parseFloat(num) / ratio;\n return pxValue === 0 ? '0' : `${pxValue}px`;\n });\n }\n }\n };\n}\n\n// PostCSS 插件标识\n(rpx2pxPlugin as PostCSSPluginCreator).postcss = true;\n","/**\n * Taro Environment Variables Injection Helper\n * \n * Automatically injects environment variables into Taro's defineConstants\n * so that they will be replaced at build time.\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { injectTaroEnv } from '@amaster.ai/vite-plugins/taro-env-inject'\n * \n * export default defineConfig({\n * defineConstants: {\n * ...injectTaroEnv()\n * }\n * })\n * ```\n */\n\nexport interface TaroEnvInjectOptions {\n /**\n * Additional environment variable names to inject\n * @default []\n */\n additional?: string[];\n \n /**\n * Whether to inject all TARO_APP_* prefixed variables\n * @default true\n */\n autoInjectTaroApp?: boolean;\n \n /**\n * Whether to inject all VITE_* prefixed variables\n * @default true\n */\n autoInjectVite?: boolean;\n}\n\n/**\n * Inject environment variables into Taro's defineConstants\n * \n * This function reads environment variables and formats them for Taro's defineConstants.\n * Taro will replace these at build time, converting `process.env.XXX` to actual values.\n */\nexport function injectTaroEnv(options: TaroEnvInjectOptions = {}): Record<string, string> {\n const {\n additional = [],\n autoInjectTaroApp = true,\n autoInjectVite = true,\n } = options;\n\n const constants: Record<string, string> = {};\n\n // Collect variable names to inject\n const varsToInject = new Set<string>(additional);\n\n // Auto-detect TARO_APP_* variables\n if (autoInjectTaroApp) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('TARO_APP_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Auto-detect VITE_* variables\n if (autoInjectVite) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('VITE_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Inject variables into defineConstants format\n varsToInject.forEach(varName => {\n const value = process.env[varName] || '';\n constants[`process.env.${varName}`] = JSON.stringify(value);\n });\n\n return constants;\n}\n\n/**\n * Inject specific environment variables for amaster.ai mini-program builds\n * \n * This is a convenience function that injects the standard environment variables\n * used by @amaster.ai/http-client for API base URL configuration.\n */\nexport function injectAmasterEnv(): Record<string, string> {\n return {\n 'process.env.TARO_APP_API_BASE_URL': JSON.stringify(process.env.TARO_APP_API_BASE_URL || ''),\n 'process.env.VITE_API_BASE_URL': JSON.stringify(process.env.VITE_API_BASE_URL || ''),\n };\n}\n","import { editorBridgePlugin } from \"./editor-bridge\";\nimport { routesExposePlugin } from \"./routes-expose\";\nimport { browserLogsPlugin } from \"./browser-logs\";\nimport { jsxSourceTaggerPlugin } from \"./tagger\";\nimport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n// import { smartReloadPlugin } from \"./smart-reload\"; // 智能重载功能开发中,暂不启用\nimport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\nimport { rpx2pxPlugin } from \"./postcss-rpx2px\";\nimport process from \"node:process\";\nimport type { Plugin } from \"vite\";\n\nexport interface DevToolsOptions {\n /**\n * 是否为 Taro 项目\n * - true: 启用 Taro 相关插件(taroStyleAdapterPlugin、rpx2pxPlugin)\n * - false: 禁用 Taro 相关插件\n * - undefined: 自动检测(通过 process.env.TARO_ENV 判断,默认为 false)\n */\n isTaro?: boolean;\n\n /**\n * Taro style adapter options\n * Controls H5 responsive scaling to match mini-program rpx behavior\n * 仅在 isTaro 为 true 时生效\n */\n styleAdapter?: TaroStyleAdapterOptions;\n\n /**\n * 是否启用 JSX Source Tagger(通过 Symbol 标记元素源码位置)\n * 默认:开发模式启用\n */\n jsxSourceTagger?: boolean;\n\n /**\n * 是否启用 Tailwind Config 同步(生成 JSON 文件)\n * 默认:开发模式启用\n */\n tailwindConfigSync?: boolean;\n\n /**\n * Tailwind 配置文件路径\n * 默认:./tailwind.config.ts\n */\n tailwindConfigPath?: string;\n}\n\n/**\n * 开发工具插件集合,简化调用,vite.config.ts 直接 devTools() 即可\n *\n * @param options 配置项\n * @param options.isTaro 是否为 Taro 项目(默认根据 TARO_ENV 自动判断)\n * @param options.styleAdapter Taro H5 样式适配配置,designWidth 应与 Taro config 一致\n * @returns Plugin[] Vite 插件数组\n *\n * @example\n * ```ts\n * // Taro 项目 - config/dev.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [devTools({ isTaro: true })]\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // React 项目 - vite.config.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * plugins: [devTools()] // isTaro 默认为 false\n * }\n * ```\n */\nexport default function devTools(options: DevToolsOptions = {}): Plugin[] {\n // 判断是否为 Taro 项目\n // 优先使用用户显式配置,否则通过环境变量判断\n const isTaro = options.isTaro ?? process.env.TARO_ENV === \"h5\";\n\n const plugins: Plugin[] = [\n // componentIdPlugin(), // 暂不启用\n editorBridgePlugin(),\n routesExposePlugin(),\n // smartReloadPlugin() // 智能重载:拦截 full-reload,静默等待重连\n ];\n\n // JSX Source Tagger - 默认开发模式启用\n if (options.jsxSourceTagger !== false) {\n plugins.push(jsxSourceTaggerPlugin());\n }\n\n // Tailwind Config Sync - 默认开发模式启用\n if (options.tailwindConfigSync !== false) {\n plugins.push(\n tailwindConfigSyncPlugin({\n configPath: options.tailwindConfigPath,\n })\n );\n }\n\n // 仅在 Taro 项目中添加 Taro 相关插件\n if (isTaro) {\n // Taro H5 样式适配(运行时)\n plugins.unshift(taroStyleAdapterPlugin(options.styleAdapter));\n\n // H5 开发模式下添加 rpx2px PostCSS 插件(编译时)\n plugins.unshift({\n name: \"dev-postcss-rpx2px-plugin\",\n apply: \"serve\",\n config(config) {\n if (typeof config.css?.postcss === \"object\") {\n // 在最前面插入,确保在 pxtransform 之前执行\n config.css?.postcss.plugins?.unshift(rpx2pxPlugin());\n }\n },\n });\n }\n\n // process.env.WORKSPACE_GIT_REPO 有这个表示是在 sandbox 里面运行,启用浏览器日志插件\n if (process.env.WORKSPACE_GIT_REPO) {\n plugins.push(browserLogsPlugin());\n }\n\n return plugins;\n}\n\nexport {\n editorBridgePlugin,\n routesExposePlugin,\n // smartReloadPlugin\n};\n\n// Export Taro environment injection helpers\nexport { injectTaroEnv, injectAmasterEnv } from \"./taro-env-inject\";\n\n// Export Taro style adapter plugin and its types\nexport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\n\n// Export PostCSS rpx2px plugin for H5 mode\nexport { rpx2pxPlugin, type Rpx2pxPluginOptions } from \"./postcss-rpx2px\";\n\n// Export tagger and tailwind config sync plugins\nexport { jsxSourceTaggerPlugin } from \"./tagger\";\nexport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n"]}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import g from'fs';import d from'path';import x from'process';import m from'fs/promises';import*as R from'esbuild';import {Buffer}from'buffer';var A=`<script>
1
+ import g from'fs';import d from'path';import x from'process';import m from'fs/promises';import*as O from'esbuild';import {Buffer}from'buffer';var A=`<script>
2
2
  document.addEventListener("click", (e) => {
3
3
  const element = e.target;
4
4
  const noJumpOut = document.body.classList.contains("forbid-jump-out")
@@ -16,10 +16,10 @@ document.addEventListener("click", (e) => {
16
16
  e.preventDefault();
17
17
  }
18
18
  });
19
- </script>`;function I(r,o){return `<script type="module">
19
+ </script>`;function I(r){return `<script type="module">
20
20
  (function() {
21
21
  const SOURCE_KEY = Symbol.for("__jsxSource__");
22
- const SESSION_KEY = "${o}";
22
+ const SESSION_KEY = "${r}";
23
23
 
24
24
  // Expose minimal API for external bridge script
25
25
  window.__AMASTER_BRIDGE__ = {
@@ -28,7 +28,7 @@ document.addEventListener("click", (e) => {
28
28
  postToParent: (type, data) => {
29
29
  window.parent.postMessage({ type, data, key: SESSION_KEY }, "*");
30
30
  },
31
- isDev: ${r},
31
+ isDev: true,
32
32
  };
33
33
 
34
34
  // Listen for bridge script URL from platform
@@ -40,15 +40,22 @@ document.addEventListener("click", (e) => {
40
40
  return;
41
41
  }
42
42
 
43
- if (type === "amaster.loadBridge" && data?.scriptUrl) {
43
+ if (type === "amaster.loadBridge" && data?.scriptContent) {
44
+ console.log("[Bridge] Loading bridge from inline script");
45
+
46
+ // Create blob URL from script content
47
+ const blob = new Blob([data.scriptContent], { type: 'application/javascript' });
48
+ const blobUrl = URL.createObjectURL(blob);
49
+
44
50
  const script = document.createElement("script");
45
- script.src = data.scriptUrl;
51
+ script.src = blobUrl;
46
52
  script.onload = () => {
47
53
  console.log("[Bridge] External script loaded");
48
- window.__AMASTER_BRIDGE__?.postToParent("amaster.bridge.ready", {});
54
+ URL.revokeObjectURL(blobUrl);
49
55
  };
50
56
  script.onerror = () => {
51
57
  console.error("[Bridge] Failed to load external script");
58
+ URL.revokeObjectURL(blobUrl);
52
59
  };
53
60
  document.head.appendChild(script);
54
61
  }
@@ -58,13 +65,13 @@ document.addEventListener("click", (e) => {
58
65
  window.__AMASTER_BRIDGE__?.postToParent("amaster.bridge.initialized", {});
59
66
  });
60
67
  })();
61
- </script>`}function b(){let r=false;return {name:"vite-plugin-editor-bridge",configResolved(o){r=o.command==="serve";},transformIndexHtml(o){if(!r)return o;let t=process.env.VITE_AMASTER_KEY||"",e=I(r,t),n=`${A}${e}</body>`;return o.replace("</body>",n)}}}function E(r){let o=false,t=r?.routesFilePath||"src/routes.tsx";return {name:"vite-plugin-routes-expose",enforce:"post",configResolved(e){o=e.command==="serve";},transform(e,n){if(!o||!n.endsWith(t))return null;try{return e.includes("window.__APP_ROUTES__")?null:{code:`${e}
68
+ </script>`}function _(){let r=false;return {name:"vite-plugin-editor-bridge",configResolved(o){r=o.command==="serve";},transformIndexHtml(o){if(!r)return o;console.log("[editorBridgePlugin] Injecting bridge script");let t=process.env.VITE_AMASTER_KEY||"",e=I(t),n=`${A}${e}</body>`;return o.replace("</body>",n)}}}function E(r){let o=false,t=r?.routesFilePath||"src/routes.tsx";return {name:"vite-plugin-routes-expose",enforce:"post",configResolved(e){o=e.command==="serve";},transform(e,n){if(!o||!n.endsWith(t))return null;try{return e.includes("window.__APP_ROUTES__")?null:{code:`${e}
62
69
 
63
70
  // Development mode: Expose routes to window.__APP_ROUTES__
64
71
  if (typeof window !== 'undefined') {
65
72
  window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];
66
73
  }
67
- `,map:null}}catch{return null}}}}function O(){let r="",o=`
74
+ `,map:null}}catch{return null}}}}function R(){let r="",o=`
68
75
  <script>
69
76
  (function() {
70
77
  'use strict';
@@ -892,7 +899,7 @@ export function jsxDEV(type, props, key, isStatic, source, self) {
892
899
 
893
900
  return _jsxDEV(type, props, key, isStatic, source, self);
894
901
  }
895
- `;function v(){let r=false,o="";return {name:"vite-plugin-jsx-source-tagger",enforce:"pre",configResolved(t){r=t.command==="serve",o=t.root;},resolveId(t,e){return r&&t==="react/jsx-dev-runtime"&&!e?.includes("\0jsx-source")?"\0jsx-source/jsx-dev-runtime":null},load(t){return r&&t==="\0jsx-source/jsx-dev-runtime"?C.replace('const PROJECT_ROOT = "";',`const PROJECT_ROOT = ${JSON.stringify(o)};`):null}}}function _(r){let o="",t=false,e=null,n=r?.configPath||"./tailwind.config.ts",a="@amaster/tailwind-config",s="\0"+a,l=async()=>{let i=d.resolve(o,n);try{return await m.access(i),i}catch{if(n.endsWith(".ts")){let u=i.replace(/\.ts$/,".js");try{return await m.access(u),u}catch{return null}}else if(n.endsWith(".js")){let u=i.replace(/\.js$/,".ts");try{return await m.access(u),u}catch{return null}}return null}},c=async()=>{try{let i=await l();if(!i)return null;let u=await m.readFile(i,"utf-8"),p=await R.transform(u,{loader:i.endsWith(".ts")?"ts":"js",format:"esm",platform:"node"}),h=await import(`data:text/javascript;base64,${Buffer.from(p.code).toString("base64")}`);if(!h?.default)throw new Error("Invalid Tailwind config structure");try{let P=(await import('tailwindcss/resolveConfig.js')).default;e=P(h.default);}catch{e=h.default;}return e}catch{return null}};return {name:"vite-plugin-tailwind-config-sync",configResolved(i){o=i.root,t=i.command==="serve";},async buildStart(){t&&await c();},resolveId(i){if(i===a)return s},async load(i){if(i===s)return e||await c(),`
902
+ `;function v(){let r=false,o="";return {name:"vite-plugin-jsx-source-tagger",enforce:"pre",configResolved(t){r=t.command==="serve",o=t.root;},resolveId(t,e){return r&&t==="react/jsx-dev-runtime"&&!e?.includes("\0jsx-source")?"\0jsx-source/jsx-dev-runtime":null},load(t){return r&&t==="\0jsx-source/jsx-dev-runtime"?C.replace('const PROJECT_ROOT = "";',`const PROJECT_ROOT = ${JSON.stringify(o)};`):null}}}function w(r){let o="",t=false,e=null,n=r?.configPath||"./tailwind.config.ts",a="@amaster/tailwind-config",s="\0"+a,l=async()=>{let i=d.resolve(o,n);try{return await m.access(i),i}catch{if(n.endsWith(".ts")){let u=i.replace(/\.ts$/,".js");try{return await m.access(u),u}catch{return null}}else if(n.endsWith(".js")){let u=i.replace(/\.js$/,".ts");try{return await m.access(u),u}catch{return null}}return null}},c=async()=>{try{let i=await l();if(!i)return null;let u=await m.readFile(i,"utf-8"),p=await O.transform(u,{loader:i.endsWith(".ts")?"ts":"js",format:"esm",platform:"node"}),h=await import(`data:text/javascript;base64,${Buffer.from(p.code).toString("base64")}`);if(!h?.default)throw new Error("Invalid Tailwind config structure");try{let P=(await import('tailwindcss/resolveConfig.js')).default;e=P(h.default);}catch{e=h.default;}return e}catch{return null}};return {name:"vite-plugin-tailwind-config-sync",configResolved(i){o=i.root,t=i.command==="serve";},async buildStart(){t&&await c();},resolveId(i){if(i===a)return s},async load(i){if(i===s)return e||await c(),`
896
903
  let config = ${JSON.stringify(e)};
897
904
 
898
905
  let _updateConfig;
@@ -914,7 +921,7 @@ export default new Proxy(config, {
914
921
  return target[prop];
915
922
  }
916
923
  });
917
- `},configureServer(i){t&&(async()=>{try{let u=await l();u&&i.watcher.add(u);}catch{}})();},async handleHotUpdate({file:i,server:u}){let p=await l();if(!p||d.normalize(i)!==d.normalize(p))return;await c();let f=u.moduleGraph.getModuleById(s);return f?(u.moduleGraph.invalidateModule(f),[f]):[]}}}function w(r={}){let{designWidth:o=375,maxWidth:t=750,baseFontSize:e=12,minRootSize:n=12,maxRootSize:a=24}=r;return {name:"vite-plugin-taro-style-adapter",apply:"serve",transformIndexHtml(s){let l=`
924
+ `},configureServer(i){t&&(async()=>{try{let u=await l();u&&i.watcher.add(u);}catch{}})();},async handleHotUpdate({file:i,server:u}){let p=await l();if(!p||d.normalize(i)!==d.normalize(p))return;await c();let f=u.moduleGraph.getModuleById(s);return f?(u.moduleGraph.invalidateModule(f),[f]):[]}}}function b(r={}){let{designWidth:o=375,maxWidth:t=750,baseFontSize:e=12,minRootSize:n=12,maxRootSize:a=24}=r;return {name:"vite-plugin-taro-style-adapter",apply:"serve",transformIndexHtml(s){let l=`
918
925
  <script data-taro-flexible="true">
919
926
  (function() {
920
927
  var designWidth = ${o};
@@ -1001,5 +1008,5 @@ export default new Proxy(config, {
1001
1008
  object-fit: contain;
1002
1009
  }
1003
1010
  </style>
1004
- </head>`)}}}function y(r={}){let{ratio:o=2}=r;return {postcssPlugin:"postcss-rpx2px",Declaration(t){t.value.includes("rpx")&&(t.value=t.value.replace(/(-?\d*\.?\d+)rpx/gi,(e,n)=>{let a=parseFloat(n)/o;return a===0?"0":`${a}px`}));}}}y.postcss=true;function k(r={}){let{additional:o=[],autoInjectTaroApp:t=true,autoInjectVite:e=true}=r,n={},a=new Set(o);return t&&Object.keys(process.env).forEach(s=>{s.startsWith("TARO_APP_")&&a.add(s);}),e&&Object.keys(process.env).forEach(s=>{s.startsWith("VITE_")&&a.add(s);}),a.forEach(s=>{let l=process.env[s]||"";n[`process.env.${s}`]=JSON.stringify(l);}),n}function L(){return {"process.env.TARO_APP_API_BASE_URL":JSON.stringify(process.env.TARO_APP_API_BASE_URL||""),"process.env.VITE_API_BASE_URL":JSON.stringify(process.env.VITE_API_BASE_URL||"")}}function q(r={}){let o=r.isTaro??x.env.TARO_ENV==="h5",t=[b(),E()];return r.jsxSourceTagger!==false&&t.push(v()),r.tailwindConfigSync!==false&&t.push(_({configPath:r.tailwindConfigPath})),o&&(t.unshift(w(r.styleAdapter)),t.unshift({name:"dev-postcss-rpx2px-plugin",apply:"serve",config(e){typeof e.css?.postcss=="object"&&e.css?.postcss.plugins?.unshift(y());}})),x.env.WORKSPACE_GIT_REPO&&t.push(O()),t}export{q as default,b as editorBridgePlugin,L as injectAmasterEnv,k as injectTaroEnv,v as jsxSourceTaggerPlugin,E as routesExposePlugin,y as rpx2pxPlugin,_ as tailwindConfigSyncPlugin,w as taroStyleAdapterPlugin};//# sourceMappingURL=index.js.map
1011
+ </head>`)}}}function y(r={}){let{ratio:o=2}=r;return {postcssPlugin:"postcss-rpx2px",Declaration(t){t.value.includes("rpx")&&(t.value=t.value.replace(/(-?\d*\.?\d+)rpx/gi,(e,n)=>{let a=parseFloat(n)/o;return a===0?"0":`${a}px`}));}}}y.postcss=true;function k(r={}){let{additional:o=[],autoInjectTaroApp:t=true,autoInjectVite:e=true}=r,n={},a=new Set(o);return t&&Object.keys(process.env).forEach(s=>{s.startsWith("TARO_APP_")&&a.add(s);}),e&&Object.keys(process.env).forEach(s=>{s.startsWith("VITE_")&&a.add(s);}),a.forEach(s=>{let l=process.env[s]||"";n[`process.env.${s}`]=JSON.stringify(l);}),n}function L(){return {"process.env.TARO_APP_API_BASE_URL":JSON.stringify(process.env.TARO_APP_API_BASE_URL||""),"process.env.VITE_API_BASE_URL":JSON.stringify(process.env.VITE_API_BASE_URL||"")}}function q(r={}){let o=r.isTaro??x.env.TARO_ENV==="h5",t=[_(),E()];return r.jsxSourceTagger!==false&&t.push(v()),r.tailwindConfigSync!==false&&t.push(w({configPath:r.tailwindConfigPath})),o&&(t.unshift(b(r.styleAdapter)),t.unshift({name:"dev-postcss-rpx2px-plugin",apply:"serve",config(e){typeof e.css?.postcss=="object"&&e.css?.postcss.plugins?.unshift(y());}})),x.env.WORKSPACE_GIT_REPO&&t.push(R()),t}export{q as default,_ as editorBridgePlugin,L as injectAmasterEnv,k as injectTaroEnv,v as jsxSourceTaggerPlugin,E as routesExposePlugin,y as rpx2pxPlugin,w as tailwindConfigSyncPlugin,b as taroStyleAdapterPlugin};//# sourceMappingURL=index.js.map
1005
1012
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/editor-bridge.ts","../src/routes-expose.ts","../src/browser-logs.ts","../src/tagger.ts","../src/tailwind-config-sync.ts","../src/taro-style-adapter.ts","../src/postcss-rpx2px.ts","../src/taro-env-inject.ts","../src/index.ts"],"names":["clickHandlerScript","getBridgeScriptContent","isDev","sessionKey","editorBridgePlugin","config","html","bridgeScript","scriptsToInject","routesExposePlugin","options","routesPath","code","id","browserLogsPlugin","logFilePath","injectedScript","workspaceDir","process","path","dir","fs","devServer","req","res","next","origin","body","chunk","logDir","error","devRuntimeCode","jsxSourceTaggerPlugin","projectRoot","importer","tailwindConfigSyncPlugin","cachedConfig","configPath","VIRTUAL_MODULE_ID","RESOLVED_VIRTUAL_MODULE_ID","findConfigFile","configFile","jsConfig","tsConfig","generateConfig","tailwindInputFile","sourceCode","result","userConfig","Buffer","resolveConfig","resolvedConfig","server","file","mod","taroStyleAdapterPlugin","designWidth","maxWidth","baseFontSize","minRootSize","maxRootSize","flexibleScript","rpx2pxPlugin","ratio","decl","_match","num","pxValue","injectTaroEnv","additional","autoInjectTaroApp","autoInjectVite","constants","varsToInject","key","varName","value","injectAmasterEnv","devTools","isTaro","plugins"],"mappings":"8IAEA,IAAMA,CAAAA,CAAqB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CAAA,CAuB3B,SAASC,CAAAA,CAAuBC,CAAAA,CAAgBC,CAAAA,CAAoB,CAClE,OAAO,CAAA;AAAA;AAAA;AAAA,uBAAA,EAGgBA,CAAU,CAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAA,EAStBD,CAAK,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CA+BlB,CAMO,SAASE,CAAAA,EAA6B,CAC3C,IAAIF,CAAAA,CAAQ,KAAA,CAEZ,OAAO,CACL,IAAA,CAAM,2BAAA,CAEN,eAAeG,CAAAA,CAAQ,CACrBH,EAAQG,CAAAA,CAAO,OAAA,GAAY,QAC7B,CAAA,CAEA,kBAAA,CAAmBC,CAAAA,CAAM,CACvB,GAAI,CAACJ,EAAO,OAAOI,CAAAA,CAEnB,IAAMH,CAAAA,CAAa,OAAA,CAAQ,IAAI,gBAAA,EAAoB,EA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A,CAAQzB,CAAAA,CAAuB7C,CAAAA,CAAQ,YAAY,CAAC,EAG5DsE,CAAAA,CAAQ,OAAA,CAAQ,CACd,IAAA,CAAM,2BAAA,CACN,KAAA,CAAO,OAAA,CACP,MAAA,CAAO3E,CAAAA,CAAQ,CACT,OAAOA,CAAAA,CAAO,GAAA,EAAK,OAAA,EAAY,QAAA,EAEjCA,CAAAA,CAAO,KAAK,OAAA,CAAQ,OAAA,EAAS,OAAA,CAAQyD,CAAAA,EAAc,EAEvD,CACF,CAAC,CAAA,CAAA,CAIC5C,CAAAA,CAAQ,GAAA,CAAI,kBAAA,EACd8D,CAAAA,CAAQ,IAAA,CAAKlE,CAAAA,EAAmB,EAG3BkE,CACT","file":"index.js","sourcesContent":["import type { Plugin } from \"vite\";\n\nconst clickHandlerScript = `<script>\ndocument.addEventListener(\"click\", (e) => {\n const element = e.target;\n const noJumpOut = document.body.classList.contains(\"forbid-jump-out\")\n if (element.hasAttribute(\"data-link-href\") && !noJumpOut) {\n const href = element.getAttribute(\"data-link-href\");\n const target = element.getAttribute(\"data-link-target\");\n if (href) {\n if (target === \"_blank\") {\n window.open(href, \"_blank\");\n } else {\n window.location.href = href;\n }\n }\n } else if(noJumpOut && element.tagName === \"A\") {\n e.preventDefault();\n }\n});\n</script>`;\n\n/**\n * Generate bridge script content with environment variables\n */\nfunction getBridgeScriptContent(isDev: boolean, sessionKey: string) {\n return `<script type=\"module\">\n(function() {\n const SOURCE_KEY = Symbol.for(\"__jsxSource__\");\n const SESSION_KEY = \"${sessionKey}\";\n\n // Expose minimal API for external bridge script\n window.__AMASTER_BRIDGE__ = {\n getSourceInfo: (element) => element?.[SOURCE_KEY],\n getSourceMap: () => window.sourceElementMap,\n postToParent: (type, data) => {\n window.parent.postMessage({ type, data, key: SESSION_KEY }, \"*\");\n },\n isDev: ${isDev},\n };\n\n // Listen for bridge script URL from platform\n window.addEventListener(\"message\", (event) => {\n const { type, data, key } = event.data;\n \n if (key !== SESSION_KEY) {\n console.warn(\"[Bridge] Invalid session key\");\n return;\n }\n \n if (type === \"amaster.loadBridge\" && data?.scriptUrl) {\n const script = document.createElement(\"script\");\n script.src = data.scriptUrl;\n script.onload = () => {\n console.log(\"[Bridge] External script loaded\");\n window.__AMASTER_BRIDGE__?.postToParent(\"amaster.bridge.ready\", {});\n };\n script.onerror = () => {\n console.error(\"[Bridge] Failed to load external script\");\n };\n document.head.appendChild(script);\n }\n });\n\n window.addEventListener(\"load\", () => {\n window.__AMASTER_BRIDGE__?.postToParent(\"amaster.bridge.initialized\", {});\n });\n})();\n</script>`;\n}\n\n/**\n * Vite plugin: Inject editor bridge script\n * Injects minimal bridge that loads external script from platform\n */\nexport function editorBridgePlugin(): Plugin {\n let isDev = false;\n\n return {\n name: \"vite-plugin-editor-bridge\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transformIndexHtml(html) {\n if (!isDev) return html;\n\n const sessionKey = process.env.VITE_AMASTER_KEY || \"\";\n const bridgeScript = getBridgeScriptContent(isDev, sessionKey);\n const scriptsToInject = `${clickHandlerScript}${bridgeScript}</body>`;\n return html.replace(\"</body>\", scriptsToInject);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Vite plugin: Expose routes to window.__APP_ROUTES__\n * Only enabled in development mode\n */\nexport function routesExposePlugin(options?: { routesFilePath?: string }): Plugin {\n let isDev = false;\n const routesPath = options?.routesFilePath || \"src/routes.tsx\";\n\n return {\n name: \"vite-plugin-routes-expose\",\n enforce: \"post\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transform(code: string, id: string) {\n if (!isDev) {\n return null;\n }\n\n if (!id.endsWith(routesPath)) {\n return null;\n }\n\n try {\n if (code.includes(\"window.__APP_ROUTES__\")) {\n return null;\n }\n\n const transformedCode = `${code}\n\n// Development mode: Expose routes to window.__APP_ROUTES__\nif (typeof window !== 'undefined') {\n window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];\n}\n`;\n\n return {\n code: transformedCode,\n map: null,\n };\n } catch {\n return null;\n }\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport { Buffer } from \"node:buffer\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\n/**\n * Browser logs collection plugin\n * Injects script into HTML head to collect console logs and network requests\n * Logs are written directly to browser.log file (same level as index.html)\n */\nexport function browserLogsPlugin(): Plugin {\n let logFilePath = \"\";\n\n // Script to inject into browser\n const injectedScript = `\n<script>\n(function() {\n 'use strict';\n \n // Log API path (provided by Vite dev server)\n var LOG_API_PATH = '/__browser__';\n \n // Write queue to ensure sequential writes\n var writeQueue = [];\n var isWriting = false;\n \n // Process write queue to ensure sequential writes\n function processWriteQueue() {\n if (isWriting || writeQueue.length === 0) return;\n \n isWriting = true;\n var entry = writeQueue.shift();\n var logText = JSON.stringify(entry);\n \n fetch(LOG_API_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: logText\n })\n .then(function(response) {\n isWriting = false;\n if (!response.ok) {\n console.warn('[BrowserLogs] Failed to write log:', response.status);\n }\n // Continue processing next item in queue\n processWriteQueue();\n })\n .catch(function(error) {\n console.warn('[BrowserLogs] Failed to write log:', error.message);\n // On failure, put log back to queue head for retry\n writeQueue.unshift(entry);\n isWriting = false;\n // Retry after delay\n setTimeout(processWriteQueue, 1000);\n });\n }\n \n // Limit headers object size\n function truncateHeaders(headers) {\n if (!headers) return headers;\n var jsonStr = JSON.stringify(headers);\n if (jsonStr.length <= MAX_HEADER_SIZE) return headers;\n return '[Headers truncated, size: ' + jsonStr.length + ']';\n }\n \n // Truncate oversized log entries\n function truncateLogEntry(entry) {\n var jsonStr = JSON.stringify(entry);\n if (jsonStr.length <= MAX_LOG_ENTRY_SIZE) {\n return entry;\n }\n \n // If oversized, progressively truncate non-critical fields\n var truncated = Object.assign({}, entry);\n \n // 1. Truncate response body first\n if (truncated.responseBody && typeof truncated.responseBody === 'string') {\n truncated.responseBody = truncated.responseBody.substring(0, 500) + '... [truncated]';\n }\n \n // 2. Truncate request body\n if (truncated.requestBody && typeof truncated.requestBody === 'string') {\n truncated.requestBody = truncated.requestBody.substring(0, 500) + '... [truncated]';\n }\n \n // 3. Truncate message\n if (truncated.message && typeof truncated.message === 'string' && truncated.message.length > 1000) {\n truncated.message = truncated.message.substring(0, 1000) + '... [truncated]';\n }\n \n // 4. Truncate stack\n if (truncated.stack && Array.isArray(truncated.stack) && truncated.stack.length > 3) {\n truncated.stack = truncated.stack.slice(0, 3);\n }\n \n // Add truncation marker\n truncated._truncated = true;\n truncated._originalSize = jsonStr.length;\n \n return truncated;\n }\n \n // Add log and send immediately (ensure order)\n function addLog(entry) {\n var truncatedEntry = truncateLogEntry(entry);\n writeQueue.push(truncatedEntry);\n processWriteQueue();\n }\n \n // ============================================\n // Console log collection\n // ============================================\n var originalConsole = {\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error,\n debug: console.debug\n };\n \n function getStackTrace() {\n var stack = new Error().stack || '';\n var lines = stack.split('\\\\n').slice(3);\n // Limit stack lines\n return lines.slice(0, MAX_STACK_LINES).map(function(line) { return line.trim(); });\n }\n \n function formatMessage(args) {\n return Array.from(args).map(function(arg) {\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg);\n } catch (e) {\n return String(arg);\n }\n }\n return String(arg);\n }).join(' ');\n }\n \n function createLogEntry(level, args) {\n return {\n type: 'console',\n timestamp: new Date().toISOString(),\n level: level,\n message: formatMessage(args),\n stack: getStackTrace()\n };\n }\n \n // Check if message should be filtered (contains [vite] text)\n function shouldFilterConsoleLog(args) {\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n if (typeof arg === 'string' && arg.indexOf('[vite]') !== -1) {\n return true;\n }\n }\n return false;\n }\n \n function wrapConsoleMethod(method, level) {\n return function() {\n var args = arguments;\n // Filter out logs containing [vite]\n if (shouldFilterConsoleLog(args)) {\n return originalConsole[method].apply(console, args);\n }\n var entry = createLogEntry(level, args);\n addLog(entry);\n return originalConsole[method].apply(console, args);\n };\n }\n \n console.log = wrapConsoleMethod('log', 'log');\n console.info = wrapConsoleMethod('info', 'info');\n console.warn = wrapConsoleMethod('warn', 'warn');\n console.error = wrapConsoleMethod('error', 'error');\n console.debug = wrapConsoleMethod('debug', 'debug');\n \n // ============================================\n // Network request collection (exclude SSE and log API requests)\n // ============================================\n \n var MAX_BODY_SIZE = 2000;\n var MAX_LOG_ENTRY_SIZE = 3000; // Max single log entry length\n var MAX_HEADER_SIZE = 500; // Max single header object length\n var MAX_STACK_LINES = 5; // Max stack lines to keep\n const FILTERED_URLS = ['/__browser__', '/builtin']; // Filter out log API and Vite built-in requests\n \n function isSSERequest(url, headers) {\n var sseUrlPatterns = ['/events', '/sse', '/stream', 'text/event-stream'];\n var urlStr = String(url).toLowerCase();\n for (var i = 0; i < sseUrlPatterns.length; i++) {\n if (urlStr.indexOf(sseUrlPatterns[i]) !== -1) {\n return true;\n }\n }\n \n if (headers) {\n if (typeof headers.get === 'function') {\n var accept = headers.get('Accept') || headers.get('accept');\n if (accept && accept.indexOf('text/event-stream') !== -1) {\n return true;\n }\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n if (key.toLowerCase() === 'accept' && headers[key].indexOf('text/event-stream') !== -1) {\n return true;\n }\n }\n }\n }\n \n return false;\n }\n \n function shouldFilterRequest(url) {\n return FILTERED_URLS.some(function(filteredUrl) {\n return String(url).indexOf(filteredUrl) !== -1;\n });\n }\n \n function formatRequestBody(body) {\n if (!body) return null;\n \n try {\n if (typeof body === 'string') {\n return body.substring(0, MAX_BODY_SIZE);\n }\n if (body instanceof FormData) {\n var formDataObj = {};\n body.forEach(function(value, key) {\n if (value instanceof File) {\n formDataObj[key] = '[File: ' + value.name + ', size: ' + value.size + ']';\n } else {\n formDataObj[key] = String(value).substring(0, 1000);\n }\n });\n return JSON.stringify(formDataObj);\n }\n if (body instanceof Blob) {\n return '[Blob: size=' + body.size + ', type=' + body.type + ']';\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return '[Binary: size=' + body.byteLength + ']';\n }\n if (body instanceof URLSearchParams) {\n return body.toString().substring(0, MAX_BODY_SIZE);\n }\n return String(body).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading body: ' + e.message + ']';\n }\n }\n \n function formatResponseBody(response, responseType) {\n if (!response) return null;\n \n try {\n if (responseType === '' || responseType === 'text') {\n return String(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'json') {\n return JSON.stringify(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'document') {\n return '[Document]';\n }\n if (responseType === 'blob') {\n return '[Blob: size=' + response.size + ']';\n }\n if (responseType === 'arraybuffer') {\n return '[ArrayBuffer: size=' + response.byteLength + ']';\n }\n return String(response).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading response: ' + e.message + ']';\n }\n }\n \n // Intercept XMLHttpRequest\n var originalXHROpen = XMLHttpRequest.prototype.open;\n var originalXHRSend = XMLHttpRequest.prototype.send;\n var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;\n \n XMLHttpRequest.prototype.open = function(method, url, async, user, password) {\n this.__requestInfo__ = {\n method: method,\n url: url,\n startTime: null,\n headers: {}\n };\n return originalXHROpen.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.setRequestHeader = function(name, value) {\n if (this.__requestInfo__ && this.__requestInfo__.headers) {\n this.__requestInfo__.headers[name] = value;\n }\n return originalXHRSetRequestHeader.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.send = function(body) {\n var xhr = this;\n var requestInfo = xhr.__requestInfo__;\n \n if (requestInfo) {\n // Skip SSE requests and filtered requests\n if (isSSERequest(requestInfo.url, requestInfo.headers) || shouldFilterRequest(requestInfo.url)) {\n return originalXHRSend.apply(this, arguments);\n }\n \n requestInfo.startTime = Date.now();\n requestInfo.requestBody = formatRequestBody(body);\n \n xhr.addEventListener('loadend', function() {\n var contentType = xhr.getResponseHeader('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return;\n }\n \n var responseHeaders = {};\n var allHeaders = xhr.getAllResponseHeaders();\n if (allHeaders) {\n allHeaders.split('\\\\r\\\\n').forEach(function(line) {\n var parts = line.split(': ');\n if (parts.length === 2) {\n responseHeaders[parts[0]] = parts[1];\n }\n });\n }\n \n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'xhr',\n method: requestInfo.method,\n url: requestInfo.url,\n status: xhr.status,\n statusText: xhr.statusText,\n duration: Date.now() - requestInfo.startTime,\n requestHeaders: truncateHeaders(requestInfo.headers),\n requestBody: requestInfo.requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseType: xhr.responseType,\n responseBody: formatResponseBody(xhr.response, xhr.responseType),\n responseSize: xhr.response ? (typeof xhr.response === 'string' ? xhr.response.length : (xhr.response.byteLength || xhr.response.size || null)) : null\n };\n \n addLog(entry);\n });\n }\n \n return originalXHRSend.apply(this, arguments);\n };\n \n // Intercept Fetch API\n var originalFetch = window.fetch;\n \n function headersToObject(headers) {\n var obj = {};\n if (!headers) return obj;\n \n if (typeof headers.forEach === 'function') {\n headers.forEach(function(value, key) {\n obj[key] = value;\n });\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n obj[key] = headers[key];\n }\n }\n return obj;\n }\n \n window.fetch = function(input, init) {\n var startTime = Date.now();\n var method = (init && init.method) || 'GET';\n var url = typeof input === 'string' ? input : input.url;\n var headers = init && init.headers;\n \n // Skip SSE requests and filtered requests\n if (isSSERequest(url, headers) || shouldFilterRequest(url)) {\n return originalFetch.apply(this, arguments);\n }\n \n var requestHeaders = headersToObject(headers);\n var requestBody = formatRequestBody(init && init.body);\n \n return originalFetch.apply(this, arguments)\n .then(function(response) {\n var contentType = response.headers.get('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return response;\n }\n \n var clonedResponse = response.clone();\n var responseHeaders = headersToObject(response.headers);\n \n clonedResponse.text().then(function(bodyText) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: bodyText ? bodyText.substring(0, MAX_BODY_SIZE) : null,\n responseSize: bodyText ? bodyText.length : null,\n ok: response.ok\n };\n \n addLog(entry);\n }).catch(function(e) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: '[Unable to read: ' + e.message + ']',\n responseSize: null,\n ok: response.ok\n };\n \n addLog(entry);\n });\n \n return response;\n })\n .catch(function(error) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: 0,\n statusText: 'Network Error',\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: null,\n responseBody: null,\n error: error.message\n };\n \n addLog(entry);\n throw error;\n });\n };\n \n // ============================================\n // Global error capture\n // ============================================\n window.addEventListener('error', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: event.message,\n stack: event.error ? event.error.stack : 'at ' + event.filename + ':' + event.lineno + ':' + event.colno\n };\n addLog(entry);\n });\n \n // ============================================\n // Vite deps 504 error capture using PerformanceObserver\n // Only captures 504 errors for node_modules/.vite resources (pre-bundled dependencies)\n // ============================================\n var reportedUrls = {}; // Track reported URLs to avoid duplicates\n \n if (typeof PerformanceObserver !== 'undefined') {\n var perfObserver = new PerformanceObserver(function(list) {\n var entries = list.getEntries();\n for (var i = 0; i < entries.length; i++) {\n var perfEntry = entries[i];\n // Only check script resources\n if (perfEntry.initiatorType !== 'script') {\n continue;\n }\n \n var resourceUrl = perfEntry.name || '';\n // Only report errors for node_modules/.vite resources\n if (resourceUrl.indexOf('node_modules/.vite') === -1 && resourceUrl.indexOf('/node_modules/.vite') === -1) {\n continue;\n }\n \n // Check if response status is 504 (Gateway Timeout)\n // responseStatus is available in Resource Timing Level 2\n var status = perfEntry.responseStatus;\n if (status === 504) {\n // Avoid duplicate reports\n if (reportedUrls[resourceUrl]) {\n continue;\n }\n reportedUrls[resourceUrl] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: resourceUrl,\n status: 504,\n message: 'Vite pre-bundled dependency returned 504 Gateway Timeout: ' + resourceUrl,\n duration: perfEntry.duration,\n transferSize: perfEntry.transferSize\n };\n addLog(entry);\n }\n }\n });\n \n try {\n perfObserver.observe({ type: 'resource', buffered: true });\n } catch (e) {\n // Fallback for browsers that don't support the options\n try {\n perfObserver.observe({ entryTypes: ['resource'] });\n } catch (e2) {\n originalConsole.warn('[BrowserLogs] PerformanceObserver not supported:', e2.message);\n }\n }\n }\n \n // ============================================\n // Script load error capture (for 504 and other network errors)\n // This captures errors that PerformanceObserver might miss\n // ============================================\n \n // Use MutationObserver to watch for dynamically added script tags\n function attachScriptErrorHandler(script) {\n if (script.__errorHandlerAttached__) return;\n script.__errorHandlerAttached__ = true;\n \n script.addEventListener('error', function(event) {\n var src = script.src || '';\n \n // Only report errors for node_modules/.vite resources\n if (src.indexOf('node_modules/.vite') === -1 && src.indexOf('/node_modules/.vite') === -1) {\n return;\n }\n \n // Avoid duplicate reports\n if (reportedUrls[src]) {\n return;\n }\n reportedUrls[src] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: src,\n status: 'load-error',\n message: 'Vite pre-bundled dependency failed to load (possibly 504 Gateway Timeout): ' + src,\n errorType: event.type\n };\n addLog(entry);\n });\n }\n \n // Attach error handlers to existing scripts\n var existingScripts = document.querySelectorAll('script[src]');\n for (var i = 0; i < existingScripts.length; i++) {\n attachScriptErrorHandler(existingScripts[i]);\n }\n \n // Watch for dynamically added scripts\n if (typeof MutationObserver !== 'undefined') {\n var scriptObserver = new MutationObserver(function(mutations) {\n for (var i = 0; i < mutations.length; i++) {\n var mutation = mutations[i];\n for (var j = 0; j < mutation.addedNodes.length; j++) {\n var node = mutation.addedNodes[j];\n if (node.nodeName === 'SCRIPT' && node.src) {\n attachScriptErrorHandler(node);\n }\n // Also check child nodes\n if (node.querySelectorAll) {\n var scripts = node.querySelectorAll('script[src]');\n for (var k = 0; k < scripts.length; k++) {\n attachScriptErrorHandler(scripts[k]);\n }\n }\n }\n }\n });\n \n scriptObserver.observe(document.documentElement, {\n childList: true,\n subtree: true\n });\n }\n \n // Also intercept document.createElement to catch scripts before they're added to DOM\n var originalCreateElement = document.createElement.bind(document);\n document.createElement = function(tagName) {\n var element = originalCreateElement(tagName);\n if (tagName.toLowerCase() === 'script') {\n // Use a setter to catch when src is set\n var originalSrc = '';\n Object.defineProperty(element, '__originalSrc__', {\n get: function() { return originalSrc; },\n set: function(val) { originalSrc = val; }\n });\n \n // Defer attaching error handler until src is set\n var srcDescriptor = Object.getOwnPropertyDescriptor(HTMLScriptElement.prototype, 'src');\n if (srcDescriptor && srcDescriptor.set) {\n var originalSrcSetter = srcDescriptor.set;\n Object.defineProperty(element, 'src', {\n get: function() {\n return srcDescriptor.get ? srcDescriptor.get.call(this) : this.getAttribute('src');\n },\n set: function(value) {\n if (originalSrcSetter) {\n originalSrcSetter.call(this, value);\n } else {\n this.setAttribute('src', value);\n }\n attachScriptErrorHandler(this);\n },\n configurable: true\n });\n }\n }\n return element;\n };\n \n window.addEventListener('unhandledrejection', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),\n stack: event.reason && event.reason.stack ? event.reason.stack : ''\n };\n addLog(entry);\n });\n \n // ============================================\n // Send remaining logs on page unload\n // ============================================\n window.addEventListener('beforeunload', function() {\n if (writeQueue.length > 0) {\n // Use sendBeacon to ensure logs are sent\n writeQueue.forEach(function(entry) {\n navigator.sendBeacon(LOG_API_PATH, JSON.stringify(entry));\n });\n writeQueue = [];\n }\n });\n \n // ============================================\n // Provide manual flush method\n // ============================================\n window.__flushBrowserLogs__ = function() {\n return new Promise(function(resolve) {\n // Wait for queue to finish processing\n function checkQueue() {\n if (writeQueue.length === 0 && !isWriting) {\n resolve();\n } else {\n setTimeout(checkQueue, 100);\n }\n }\n checkQueue();\n });\n };\n \n // Provide method to get queue status\n window.__getBrowserLogsStatus__ = function() {\n return {\n queueLength: writeQueue.length,\n isWriting: isWriting\n };\n };\n \n originalConsole.log('[BrowserLogs] Log collection started');\n})();\n</script>`;\n\n return {\n name: \"vite-plugin-browser-logs\",\n\n configResolved(config) {\n // Determine log file path: use WORKSPACE_DIR env var (set by PM2/Docker),\n // or find the nearest directory containing package.json from config.root,\n // to ensure browser.log is always at the workspace root level.\n const workspaceDir = process.env.WORKSPACE_DIR;\n if (workspaceDir) {\n logFilePath = path.join(workspaceDir, \"browser.log\");\n } else {\n // Fallback: walk up from config.root to find directory with package.json\n let dir = config.root || process.cwd();\n while (dir !== path.dirname(dir)) {\n if (fs.existsSync(path.join(dir, \"package.json\"))) {\n break;\n }\n dir = path.dirname(dir);\n }\n logFilePath = path.join(dir, \"browser.log\");\n }\n },\n\n configureServer(devServer) {\n // Add log write API\n devServer.middlewares.use((req, res, next) => {\n if (req.url === \"/__browser__\" && req.method === \"POST\") {\n // Get request origin, dynamically set CORS headers to avoid protocol mismatch\n const origin = req.headers.origin || \"*\";\n\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n try {\n // Ensure log directory exists\n const logDir = path.dirname(logFilePath);\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n // Append to log file\n fs.appendFileSync(logFilePath, `${body}\\n`, \"utf-8\");\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: true }));\n } catch (error) {\n console.error(\"[BrowserLogs] Write error:\", error);\n res.writeHead(500, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: false, error: String(error) }));\n }\n });\n } else if (req.url === \"/__browser__\" && req.method === \"OPTIONS\") {\n // Handle CORS preflight request\n const origin = req.headers.origin || \"*\";\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n res.end();\n } else if (req.url === \"/__browser__\") {\n const origin = req.headers.origin || \"*\";\n res.writeHead(405, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n });\n res.end(JSON.stringify({ error: \"Method not allowed\" }));\n } else {\n next();\n }\n });\n\n console.log(\"[BrowserLogs] Logs will be written to:\", logFilePath);\n },\n\n transformIndexHtml(html) {\n // Insert script after <head> tag to ensure earliest execution\n return html.replace(/<head([^>]*)>/i, `<head$1>${injectedScript}`);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Runtime code that will be injected to replace react/jsx-dev-runtime\n * This code tags DOM elements with source information using refs\n */\nconst devRuntimeCode = `\nimport * as React from \"react\";\nimport * as ReactJSXDevRuntime from \"react/jsx-dev-runtime\";\n\nconst _jsxDEV = ReactJSXDevRuntime.jsxDEV;\nexport const Fragment = ReactJSXDevRuntime.Fragment;\n\nconst SOURCE_KEY = Symbol.for(\"__jsxSource__\");\nconst PROJECT_ROOT = \"\";\n\nconst cleanFileName = (fileName) => {\n if (!fileName) return \"\";\n // Remove project root prefix to get relative path\n if (PROJECT_ROOT && fileName.startsWith(PROJECT_ROOT)) {\n const relative = fileName.slice(PROJECT_ROOT.length);\n return relative.startsWith(\"/\") ? relative.slice(1) : relative;\n }\n return fileName;\n};\n\n// Global map to track elements by source location\nconst sourceElementMap = new Map();\nwindow.sourceElementMap = sourceElementMap;\n\nfunction getSourceKey(sourceInfo) {\n return \\`\\${cleanFileName(sourceInfo.fileName)}:\\${sourceInfo.lineNumber}:\\${sourceInfo.columnNumber}\\`;\n}\n\nfunction unregisterElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n const refs = sourceElementMap.get(key);\n if (refs) {\n for (const ref of refs) {\n if (ref.deref() === node) {\n refs.delete(ref);\n break;\n }\n }\n if (refs.size === 0) {\n sourceElementMap.delete(key);\n }\n }\n}\n\nfunction registerElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n if (!sourceElementMap.has(key)) {\n sourceElementMap.set(key, new Set());\n }\n sourceElementMap.get(key).add(new WeakRef(node));\n}\n\nfunction getTypeName(type) {\n if (typeof type === \"string\") return type;\n if (typeof type === \"function\") return type.displayName || type.name || \"Unknown\";\n if (typeof type === \"object\" && type !== null) {\n return type.displayName || type.render?.displayName || type.render?.name || \"Unknown\";\n }\n return \"Unknown\";\n}\n\nexport function jsxDEV(type, props, key, isStatic, source, self) {\n // For custom components, tag their rendered output\n if (source?.fileName && typeof type !== \"string\" && type !== Fragment) {\n const typeName = getTypeName(type);\n const jsxSourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: typeName,\n };\n\n const originalRef = props?.ref;\n \n // Check if component can safely receive refs\n // - forwardRef components have $$typeof symbol\n // - Class components have prototype.isReactComponent\n // - If there's already a ref, the component expects it\n const isForwardRef = type.$$typeof === Symbol.for('react.forward_ref');\n const isClassComponent = typeof type === 'function' && type.prototype?.isReactComponent;\n const hasExistingRef = originalRef !== undefined;\n \n const canReceiveRef = isForwardRef || isClassComponent || hasExistingRef;\n \n if (canReceiveRef) {\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n if (!node[SOURCE_KEY]) {\n node[SOURCE_KEY] = jsxSourceInfo;\n registerElement(node, jsxSourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n }\n\n // For host elements (div, span, etc.), tag with source info\n if (source?.fileName && typeof type === \"string\") {\n const sourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: type,\n };\n\n const originalRef = props?.ref;\n\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n const existingSource = node[SOURCE_KEY];\n if (existingSource) {\n if (getSourceKey(existingSource) !== getSourceKey(sourceInfo)) {\n unregisterElement(node, existingSource);\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n } else {\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n}\n`;\n\n/**\n * Vite plugin: JSX Source Tagger\n * Intercepts react/jsx-dev-runtime to add source information to DOM elements\n * Only enabled in development mode\n */\nexport function jsxSourceTaggerPlugin(): Plugin {\n let isDev = false;\n let projectRoot = \"\";\n\n return {\n name: \"vite-plugin-jsx-source-tagger\",\n enforce: \"pre\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n projectRoot = config.root;\n },\n\n resolveId(id, importer) {\n if (!isDev) return null;\n\n // Intercept react/jsx-dev-runtime imports\n if (id === \"react/jsx-dev-runtime\" && !importer?.includes(\"\\0jsx-source\")) {\n return \"\\0jsx-source/jsx-dev-runtime\";\n }\n return null;\n },\n\n load(id) {\n if (!isDev) return null;\n\n // Return our custom runtime code with injected projectRoot\n if (id === \"\\0jsx-source/jsx-dev-runtime\") {\n return devRuntimeCode.replace(\n 'const PROJECT_ROOT = \"\";',\n `const PROJECT_ROOT = ${JSON.stringify(projectRoot)};`\n );\n }\n return null;\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport * as esbuild from \"esbuild\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Vite plugin: Tailwind Config Sync\n * Generates a JSON file from tailwind.config.ts for runtime access\n * Only enabled in development mode\n */\nexport function tailwindConfigSyncPlugin(options?: { configPath?: string }): Plugin {\n let projectRoot = \"\";\n let isDev = false;\n let cachedConfig: Record<string, unknown> | null = null;\n\n const configPath = options?.configPath || \"./tailwind.config.ts\";\n const VIRTUAL_MODULE_ID = \"@amaster/tailwind-config\";\n const RESOLVED_VIRTUAL_MODULE_ID = \"\\0\" + VIRTUAL_MODULE_ID;\n\n const findConfigFile = async (): Promise<string | null> => {\n const configFile = path.resolve(projectRoot, configPath);\n\n try {\n await fs.access(configFile);\n return configFile;\n } catch {\n // If specified config doesn't exist, try alternative extensions\n if (configPath.endsWith(\".ts\")) {\n const jsConfig = configFile.replace(/\\.ts$/, \".js\");\n try {\n await fs.access(jsConfig);\n return jsConfig;\n } catch {\n return null;\n }\n } else if (configPath.endsWith(\".js\")) {\n const tsConfig = configFile.replace(/\\.js$/, \".ts\");\n try {\n await fs.access(tsConfig);\n return tsConfig;\n } catch {\n return null;\n }\n }\n return null;\n }\n };\n\n const generateConfig = async (): Promise<Record<string, unknown> | null> => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (!tailwindInputFile) return null;\n\n const sourceCode = await fs.readFile(tailwindInputFile, \"utf-8\");\n const result = await esbuild.transform(sourceCode, {\n loader: tailwindInputFile.endsWith(\".ts\") ? \"ts\" : \"js\",\n format: \"esm\",\n platform: \"node\",\n });\n\n const dataUrl = `data:text/javascript;base64,${Buffer.from(result.code).toString(\"base64\")}`;\n const userConfig = await import(dataUrl);\n\n if (!userConfig?.default) {\n throw new Error(\"Invalid Tailwind config structure\");\n }\n\n // Try to resolve with tailwindcss, fallback to raw config\n try {\n const resolveConfig = (await import(\"tailwindcss/resolveConfig.js\")).default;\n cachedConfig = resolveConfig(userConfig.default);\n } catch {\n cachedConfig = userConfig.default;\n }\n\n return cachedConfig;\n } catch {\n return null;\n }\n };\n\n return {\n name: \"vite-plugin-tailwind-config-sync\",\n\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n isDev = resolvedConfig.command === \"serve\";\n },\n\n async buildStart() {\n if (!isDev) return;\n await generateConfig();\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return RESOLVED_VIRTUAL_MODULE_ID;\n }\n },\n\n async load(id) {\n if (id === RESOLVED_VIRTUAL_MODULE_ID) {\n if (!cachedConfig) {\n await generateConfig();\n }\n\n // Generate code with HMR support\n const code = `\nlet config = ${JSON.stringify(cachedConfig)};\n\nlet _updateConfig;\nif (import.meta.hot) {\n // Accept self updates\n import.meta.hot.accept((newModule) => {\n if (newModule && _updateConfig) {\n _updateConfig(newModule.default);\n }\n });\n}\n\nexport default new Proxy(config, {\n get(target, prop) {\n if (prop === 'then') return undefined;\n if (prop === '__setUpdater') {\n return (fn) => { _updateConfig = fn; };\n }\n return target[prop];\n }\n});\n`;\n return code;\n }\n },\n\n configureServer(server) {\n if (!isDev) return;\n\n (async () => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (tailwindInputFile) {\n server.watcher.add(tailwindInputFile);\n }\n } catch {\n // Ignore errors\n }\n })();\n },\n\n async handleHotUpdate({ file, server }) {\n const tailwindInputFile = await findConfigFile();\n\n if (!tailwindInputFile || path.normalize(file) !== path.normalize(tailwindInputFile)) {\n return;\n }\n\n await generateConfig();\n\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n return [mod];\n }\n\n return [];\n },\n };\n}\n","import type { Plugin } from 'vite';\n\nexport interface TaroStyleAdapterOptions {\n /**\n * Design width for responsive scaling (default: 375)\n * Should match Taro config's designWidth\n */\n designWidth?: number;\n \n /**\n * Maximum viewport width to scale (default: 750)\n * Beyond this width, font-size stays fixed\n */\n maxWidth?: number;\n\n /**\n * Base font size in pixels (default: 12)\n * Should match Taro config's baseFontSize\n */\n baseFontSize?: number;\n\n /**\n * Minimum root font size in pixels (default: 12)\n * Should match Taro config's minRootSize\n */\n minRootSize?: number;\n\n /**\n * Maximum root font size in pixels (default: 24)\n * Should match Taro config's maxRootSize\n */\n maxRootSize?: number;\n}\n\n/**\n * Taro H5 样式适配插件\n * \n * 功能:\n * 1. 动态计算根字号,使 H5 的 rem 与小程序的 rpx 行为对齐\n * 2. 隐藏 Taro 页面容器的滚动条,用于编辑器 iframe 预览\n * \n * 原理:\n * - 小程序 rpx: 1rpx = 屏幕宽度 / 750\n * - H5 rem: Taro 把 rpx 转成 rem,基于 baseFontSize\n * - 本插件动态设置 html font-size,使 rem 的实际像素值与 rpx 对齐\n * \n * 注意:此插件会覆盖 Taro 默认注入的根字号脚本,配置需与 Taro pxtransform 保持一致\n * \n * @example\n * ```ts\n * // In Taro config/dev.ts\n * import { taroStyleAdapterPlugin } from '@amaster.ai/vite-plugins'\n * \n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [\n * taroStyleAdapterPlugin({ \n * designWidth: 375,\n * baseFontSize: 12,\n * minRootSize: 12,\n * maxRootSize: 24\n * })\n * ]\n * }\n * }\n * ```\n */\nexport function taroStyleAdapterPlugin(options: TaroStyleAdapterOptions = {}): Plugin {\n const { \n designWidth = 375, \n maxWidth = 750,\n baseFontSize = 12,\n minRootSize = 12,\n maxRootSize = 24\n } = options;\n \n return {\n name: 'vite-plugin-taro-style-adapter',\n apply: 'serve', // 仅在开发模式下生效\n transformIndexHtml(html) {\n // 动态根字号脚本\n // 公式:fontSize = (clientWidth / designWidth) * baseFontSize\n // 当 designWidth=375, baseFontSize=12 时:\n // - 375px 屏幕 → 12px (1rem = 12px)\n // - 750px 屏幕 → 24px (1rem = 24px)\n // 这样 rem 值在不同屏幕宽度下的视觉比例与小程序 rpx 一致\n const flexibleScript = `\n<script data-taro-flexible=\"true\">\n(function() {\n var designWidth = ${designWidth};\n var maxWidth = ${maxWidth};\n var baseFontSize = ${baseFontSize};\n var minRootSize = ${minRootSize};\n var maxRootSize = ${maxRootSize};\n \n function setRootFontSize() {\n var docEl = document.documentElement;\n var clientWidth = docEl.clientWidth;\n \n // 限制最大宽度\n if (clientWidth > maxWidth) {\n clientWidth = maxWidth;\n }\n \n // 计算根字号: (屏幕宽度 / 设计稿宽度) * 基准字号\n var fontSize = (clientWidth / designWidth) * baseFontSize;\n \n // 应用最小/最大限制\n if (fontSize < minRootSize) {\n fontSize = minRootSize;\n } else if (fontSize > maxRootSize) {\n fontSize = maxRootSize;\n }\n \n docEl.style.fontSize = fontSize + 'px';\n }\n \n setRootFontSize();\n \n // 监听窗口变化\n window.addEventListener('resize', setRootFontSize);\n window.addEventListener('orientationchange', setRootFontSize);\n \n // 页面显示时重新计算(解决某些浏览器的 bug)\n document.addEventListener('DOMContentLoaded', setRootFontSize);\n})();\n</script>\n`;\n\n // 滚动条隐藏样式 + Taro Image 组件修复\n const styles = `\n<style data-taro-adapter=\"true\">\n /* 仅 H5 生效:隐藏 Taro 页面容器滚动条,但仍可滚动 */\n .taro_page {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro_page::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /* 隐藏 Taro ScrollView 组件的滚动条 */\n .taro-scroll-view__scroll-y,\n .taro-scroll-view__scroll-x {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro-scroll-view__scroll-y::-webkit-scrollbar,\n .taro-scroll-view__scroll-x::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /*\n * 修复 Taro Image 组件在 H5 下的尺寸问题\n * \n * 问题:Taro Image 组件使用 aspectFit 模式时,内部 img 使用 max-width/max-height: 100%\n * 导致小尺寸图片(如 SVG 图标)无法按指定尺寸显示,只显示原始尺寸\n * \n * 解决:让 img 填满 taro-image-core 容器,由容器控制尺寸\n */\n taro-image-core img.taro-img__mode-aspectfit {\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n position: static;\n transform: none;\n object-fit: contain;\n }\n</style>\n`;\n \n // 在 </head> 之前插入脚本和样式\n return html.replace('</head>', `${flexibleScript}${styles}</head>`);\n }\n };\n}\n","/**\n * PostCSS 插件:H5 模式下将 rpx 预转换为 px\n *\n * 问题背景:\n * - Taro 的 pxtransform 在 H5 模式下会处理 rpx,但它把 rpx 值直接除以 rootValue\n * - 导致 96rpx 被转成 8rem(96/12),实际显示为 96px\n * - 而正确应该是:96rpx = 48px = 4rem = 48px\n *\n * 解决方案:\n * - 在 pxtransform 之前,先把 rpx 转成 px(rpx / 2)\n * - 然后 pxtransform 会正确地把 px 转成 rem(px / 12)\n *\n * 转换链路:96rpx → 48px → 4rem → 48px(正确)\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { rpx2pxPlugin } from '@amaster.ai/vite-plugins'\n * \n * // 在 postcss-config-loader-plugin 中使用\n * {\n * name: 'postcss-config-loader-plugin',\n * config(config) {\n * if (typeof config.css?.postcss === 'object') {\n * config.css?.postcss.plugins?.unshift(tailwindcss())\n * // H5 模式下添加 rpx2px 插件\n * if (process.env.TARO_ENV === 'h5') {\n * config.css?.postcss.plugins?.unshift(rpx2pxPlugin())\n * }\n * }\n * }\n * }\n * ```\n */\n\nexport interface Rpx2pxPluginOptions {\n /**\n * rpx 到 px 的转换比例(默认 2)\n * 即 1rpx = 1/ratio px\n * 默认值 2 表示 2rpx = 1px(基于 375 设计稿)\n */\n ratio?: number;\n}\n\ninterface PostCSSDeclaration {\n value: string;\n}\n\ninterface PostCSSPlugin {\n postcssPlugin: string;\n Declaration: (decl: PostCSSDeclaration) => void;\n}\n\ntype PostCSSPluginCreator = {\n (): PostCSSPlugin;\n postcss: boolean;\n};\n\nexport function rpx2pxPlugin(options: Rpx2pxPluginOptions = {}): PostCSSPlugin {\n const { ratio = 2 } = options;\n \n return {\n postcssPlugin: 'postcss-rpx2px',\n Declaration(decl: PostCSSDeclaration) {\n if (decl.value.includes('rpx')) {\n decl.value = decl.value.replace(/(-?\\d*\\.?\\d+)rpx/gi, (_match: string, num: string) => {\n const pxValue = parseFloat(num) / ratio;\n return pxValue === 0 ? '0' : `${pxValue}px`;\n });\n }\n }\n };\n}\n\n// PostCSS 插件标识\n(rpx2pxPlugin as PostCSSPluginCreator).postcss = true;\n","/**\n * Taro Environment Variables Injection Helper\n * \n * Automatically injects environment variables into Taro's defineConstants\n * so that they will be replaced at build time.\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { injectTaroEnv } from '@amaster.ai/vite-plugins/taro-env-inject'\n * \n * export default defineConfig({\n * defineConstants: {\n * ...injectTaroEnv()\n * }\n * })\n * ```\n */\n\nexport interface TaroEnvInjectOptions {\n /**\n * Additional environment variable names to inject\n * @default []\n */\n additional?: string[];\n \n /**\n * Whether to inject all TARO_APP_* prefixed variables\n * @default true\n */\n autoInjectTaroApp?: boolean;\n \n /**\n * Whether to inject all VITE_* prefixed variables\n * @default true\n */\n autoInjectVite?: boolean;\n}\n\n/**\n * Inject environment variables into Taro's defineConstants\n * \n * This function reads environment variables and formats them for Taro's defineConstants.\n * Taro will replace these at build time, converting `process.env.XXX` to actual values.\n */\nexport function injectTaroEnv(options: TaroEnvInjectOptions = {}): Record<string, string> {\n const {\n additional = [],\n autoInjectTaroApp = true,\n autoInjectVite = true,\n } = options;\n\n const constants: Record<string, string> = {};\n\n // Collect variable names to inject\n const varsToInject = new Set<string>(additional);\n\n // Auto-detect TARO_APP_* variables\n if (autoInjectTaroApp) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('TARO_APP_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Auto-detect VITE_* variables\n if (autoInjectVite) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('VITE_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Inject variables into defineConstants format\n varsToInject.forEach(varName => {\n const value = process.env[varName] || '';\n constants[`process.env.${varName}`] = JSON.stringify(value);\n });\n\n return constants;\n}\n\n/**\n * Inject specific environment variables for amaster.ai mini-program builds\n * \n * This is a convenience function that injects the standard environment variables\n * used by @amaster.ai/http-client for API base URL configuration.\n */\nexport function injectAmasterEnv(): Record<string, string> {\n return {\n 'process.env.TARO_APP_API_BASE_URL': JSON.stringify(process.env.TARO_APP_API_BASE_URL || ''),\n 'process.env.VITE_API_BASE_URL': JSON.stringify(process.env.VITE_API_BASE_URL || ''),\n };\n}\n","import { editorBridgePlugin } from \"./editor-bridge\";\nimport { routesExposePlugin } from \"./routes-expose\";\nimport { browserLogsPlugin } from \"./browser-logs\";\nimport { jsxSourceTaggerPlugin } from \"./tagger\";\nimport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n// import { smartReloadPlugin } from \"./smart-reload\"; // 智能重载功能开发中,暂不启用\nimport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\nimport { rpx2pxPlugin } from \"./postcss-rpx2px\";\nimport process from \"node:process\";\nimport type { Plugin } from \"vite\";\n\nexport interface DevToolsOptions {\n /**\n * 是否为 Taro 项目\n * - true: 启用 Taro 相关插件(taroStyleAdapterPlugin、rpx2pxPlugin)\n * - false: 禁用 Taro 相关插件\n * - undefined: 自动检测(通过 process.env.TARO_ENV 判断,默认为 false)\n */\n isTaro?: boolean;\n\n /**\n * Taro style adapter options\n * Controls H5 responsive scaling to match mini-program rpx behavior\n * 仅在 isTaro 为 true 时生效\n */\n styleAdapter?: TaroStyleAdapterOptions;\n\n /**\n * 是否启用 JSX Source Tagger(通过 Symbol 标记元素源码位置)\n * 默认:开发模式启用\n */\n jsxSourceTagger?: boolean;\n\n /**\n * 是否启用 Tailwind Config 同步(生成 JSON 文件)\n * 默认:开发模式启用\n */\n tailwindConfigSync?: boolean;\n\n /**\n * Tailwind 配置文件路径\n * 默认:./tailwind.config.ts\n */\n tailwindConfigPath?: string;\n}\n\n/**\n * 开发工具插件集合,简化调用,vite.config.ts 直接 devTools() 即可\n *\n * @param options 配置项\n * @param options.isTaro 是否为 Taro 项目(默认根据 TARO_ENV 自动判断)\n * @param options.styleAdapter Taro H5 样式适配配置,designWidth 应与 Taro config 一致\n * @returns Plugin[] Vite 插件数组\n *\n * @example\n * ```ts\n * // Taro 项目 - config/dev.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [devTools({ isTaro: true })]\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // React 项目 - vite.config.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * plugins: [devTools()] // isTaro 默认为 false\n * }\n * ```\n */\nexport default function devTools(options: DevToolsOptions = {}): Plugin[] {\n // 判断是否为 Taro 项目\n // 优先使用用户显式配置,否则通过环境变量判断\n const isTaro = options.isTaro ?? process.env.TARO_ENV === \"h5\";\n\n const plugins: Plugin[] = [\n // componentIdPlugin(), // 暂不启用\n editorBridgePlugin(),\n routesExposePlugin(),\n // smartReloadPlugin() // 智能重载:拦截 full-reload,静默等待重连\n ];\n\n // JSX Source Tagger - 默认开发模式启用\n if (options.jsxSourceTagger !== false) {\n plugins.push(jsxSourceTaggerPlugin());\n }\n\n // Tailwind Config Sync - 默认开发模式启用\n if (options.tailwindConfigSync !== false) {\n plugins.push(\n tailwindConfigSyncPlugin({\n configPath: options.tailwindConfigPath,\n })\n );\n }\n\n // 仅在 Taro 项目中添加 Taro 相关插件\n if (isTaro) {\n // Taro H5 样式适配(运行时)\n plugins.unshift(taroStyleAdapterPlugin(options.styleAdapter));\n\n // H5 开发模式下添加 rpx2px PostCSS 插件(编译时)\n plugins.unshift({\n name: \"dev-postcss-rpx2px-plugin\",\n apply: \"serve\",\n config(config) {\n if (typeof config.css?.postcss === \"object\") {\n // 在最前面插入,确保在 pxtransform 之前执行\n config.css?.postcss.plugins?.unshift(rpx2pxPlugin());\n }\n },\n });\n }\n\n // process.env.WORKSPACE_GIT_REPO 有这个表示是在 sandbox 里面运行,启用浏览器日志插件\n if (process.env.WORKSPACE_GIT_REPO) {\n plugins.push(browserLogsPlugin());\n }\n\n return plugins;\n}\n\nexport {\n editorBridgePlugin,\n routesExposePlugin,\n // smartReloadPlugin\n};\n\n// Export Taro environment injection helpers\nexport { injectTaroEnv, injectAmasterEnv } from \"./taro-env-inject\";\n\n// Export Taro style adapter plugin and its types\nexport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\n\n// Export PostCSS rpx2px plugin for H5 mode\nexport { rpx2pxPlugin, type Rpx2pxPluginOptions } from \"./postcss-rpx2px\";\n\n// Export tagger and tailwind config sync plugins\nexport { jsxSourceTaggerPlugin } from \"./tagger\";\nexport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n"]}
1
+ {"version":3,"sources":["../src/editor-bridge.ts","../src/routes-expose.ts","../src/browser-logs.ts","../src/tagger.ts","../src/tailwind-config-sync.ts","../src/taro-style-adapter.ts","../src/postcss-rpx2px.ts","../src/taro-env-inject.ts","../src/index.ts"],"names":["clickHandlerScript","getBridgeScriptContent","sessionKey","editorBridgePlugin","isDev","config","html","bridgeScript","scriptsToInject","routesExposePlugin","options","routesPath","code","id","browserLogsPlugin","logFilePath","injectedScript","workspaceDir","process","path","dir","fs","devServer","req","res","next","origin","body","chunk","logDir","error","devRuntimeCode","jsxSourceTaggerPlugin","projectRoot","importer","tailwindConfigSyncPlugin","cachedConfig","configPath","VIRTUAL_MODULE_ID","RESOLVED_VIRTUAL_MODULE_ID","findConfigFile","configFile","jsConfig","tsConfig","generateConfig","tailwindInputFile","sourceCode","result","userConfig","Buffer","resolveConfig","resolvedConfig","server","file","mod","taroStyleAdapterPlugin","designWidth","maxWidth","baseFontSize","minRootSize","maxRootSize","flexibleScript","rpx2pxPlugin","ratio","decl","_match","num","pxValue","injectTaroEnv","additional","autoInjectTaroApp","autoInjectVite","constants","varsToInject","key","varName","value","injectAmasterEnv","devTools","isTaro","plugins"],"mappings":"8IAEA,IAAMA,CAAAA,CAAqB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CAAA,CAuB3B,SAASC,CAAAA,CAAuBC,CAAAA,CAAoB,CAClD,OAAO,CAAA;AAAA;AAAA;AAAA,uBAAA,EAGgBA,CAAU,CAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,SAAA,CA+CnC,CAMO,SAASC,CAAAA,EAA6B,CAC3C,IAAIC,CAAAA,CAAQ,KAAA,CAEZ,OAAO,CACL,IAAA,CAAM,2BAAA,CAEN,eAAeC,CAAAA,CAAQ,CACrBD,CAAAA,CAAQC,CAAAA,CAAO,OAAA,GAAY,QAC7B,EAEA,kBAAA,CAAmBC,CAAAA,CAAM,CACvB,GAAI,CAACF,CAAAA,CAAO,OAAOE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B,UAAA,CAAYzB,CAAAA,CAAQ,kBACtB,CAAC,CACH,CAAA,CAIEqE,CAAAA,GAEFC,CAAAA,CAAQ,OAAA,CAAQzB,CAAAA,CAAuB7C,CAAAA,CAAQ,YAAY,CAAC,EAG5DsE,CAAAA,CAAQ,OAAA,CAAQ,CACd,IAAA,CAAM,2BAAA,CACN,KAAA,CAAO,OAAA,CACP,MAAA,CAAO3E,CAAAA,CAAQ,CACT,OAAOA,CAAAA,CAAO,GAAA,EAAK,OAAA,EAAY,QAAA,EAEjCA,CAAAA,CAAO,KAAK,OAAA,CAAQ,OAAA,EAAS,OAAA,CAAQyD,CAAAA,EAAc,EAEvD,CACF,CAAC,CAAA,CAAA,CAIC5C,CAAAA,CAAQ,GAAA,CAAI,kBAAA,EACd8D,CAAAA,CAAQ,IAAA,CAAKlE,CAAAA,EAAmB,EAG3BkE,CACT","file":"index.js","sourcesContent":["import type { Plugin } from \"vite\";\n\nconst clickHandlerScript = `<script>\ndocument.addEventListener(\"click\", (e) => {\n const element = e.target;\n const noJumpOut = document.body.classList.contains(\"forbid-jump-out\")\n if (element.hasAttribute(\"data-link-href\") && !noJumpOut) {\n const href = element.getAttribute(\"data-link-href\");\n const target = element.getAttribute(\"data-link-target\");\n if (href) {\n if (target === \"_blank\") {\n window.open(href, \"_blank\");\n } else {\n window.location.href = href;\n }\n }\n } else if(noJumpOut && element.tagName === \"A\") {\n e.preventDefault();\n }\n});\n</script>`;\n\n/**\n * Generate bridge script content with environment variables\n */\nfunction getBridgeScriptContent(sessionKey: string) {\n return `<script type=\"module\">\n(function() {\n const SOURCE_KEY = Symbol.for(\"__jsxSource__\");\n const SESSION_KEY = \"${sessionKey}\";\n\n // Expose minimal API for external bridge script\n window.__AMASTER_BRIDGE__ = {\n getSourceInfo: (element) => element?.[SOURCE_KEY],\n getSourceMap: () => window.sourceElementMap,\n postToParent: (type, data) => {\n window.parent.postMessage({ type, data, key: SESSION_KEY }, \"*\");\n },\n isDev: true,\n };\n\n // Listen for bridge script URL from platform\n window.addEventListener(\"message\", (event) => {\n const { type, data, key } = event.data;\n \n if (key !== SESSION_KEY) {\n console.warn(\"[Bridge] Invalid session key\");\n return;\n }\n \n if (type === \"amaster.loadBridge\" && data?.scriptContent) {\n console.log(\"[Bridge] Loading bridge from inline script\");\n \n // Create blob URL from script content\n const blob = new Blob([data.scriptContent], { type: 'application/javascript' });\n const blobUrl = URL.createObjectURL(blob);\n \n const script = document.createElement(\"script\");\n script.src = blobUrl;\n script.onload = () => {\n console.log(\"[Bridge] External script loaded\");\n URL.revokeObjectURL(blobUrl);\n };\n script.onerror = () => {\n console.error(\"[Bridge] Failed to load external script\");\n URL.revokeObjectURL(blobUrl);\n };\n document.head.appendChild(script);\n }\n });\n\n window.addEventListener(\"load\", () => {\n window.__AMASTER_BRIDGE__?.postToParent(\"amaster.bridge.initialized\", {});\n });\n})();\n</script>`;\n}\n\n/**\n * Vite plugin: Inject editor bridge script\n * Injects minimal bridge that loads external script from platform\n */\nexport function editorBridgePlugin(): Plugin {\n let isDev = false;\n\n return {\n name: \"vite-plugin-editor-bridge\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transformIndexHtml(html) {\n if (!isDev) return html;\n\n console.log(\"[editorBridgePlugin] Injecting bridge script\");\n const sessionKey = process.env.VITE_AMASTER_KEY || \"\";\n const bridgeScript = getBridgeScriptContent(sessionKey);\n const scriptsToInject = `${clickHandlerScript}${bridgeScript}</body>`;\n return html.replace(\"</body>\", scriptsToInject);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Vite plugin: Expose routes to window.__APP_ROUTES__\n * Only enabled in development mode\n */\nexport function routesExposePlugin(options?: { routesFilePath?: string }): Plugin {\n let isDev = false;\n const routesPath = options?.routesFilePath || \"src/routes.tsx\";\n\n return {\n name: \"vite-plugin-routes-expose\",\n enforce: \"post\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n },\n\n transform(code: string, id: string) {\n if (!isDev) {\n return null;\n }\n\n if (!id.endsWith(routesPath)) {\n return null;\n }\n\n try {\n if (code.includes(\"window.__APP_ROUTES__\")) {\n return null;\n }\n\n const transformedCode = `${code}\n\n// Development mode: Expose routes to window.__APP_ROUTES__\nif (typeof window !== 'undefined') {\n window.__APP_ROUTES__ = typeof routes !== 'undefined' && Array.isArray(routes) ? routes : [];\n}\n`;\n\n return {\n code: transformedCode,\n map: null,\n };\n } catch {\n return null;\n }\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport { Buffer } from \"node:buffer\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\n/**\n * Browser logs collection plugin\n * Injects script into HTML head to collect console logs and network requests\n * Logs are written directly to browser.log file (same level as index.html)\n */\nexport function browserLogsPlugin(): Plugin {\n let logFilePath = \"\";\n\n // Script to inject into browser\n const injectedScript = `\n<script>\n(function() {\n 'use strict';\n \n // Log API path (provided by Vite dev server)\n var LOG_API_PATH = '/__browser__';\n \n // Write queue to ensure sequential writes\n var writeQueue = [];\n var isWriting = false;\n \n // Process write queue to ensure sequential writes\n function processWriteQueue() {\n if (isWriting || writeQueue.length === 0) return;\n \n isWriting = true;\n var entry = writeQueue.shift();\n var logText = JSON.stringify(entry);\n \n fetch(LOG_API_PATH, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: logText\n })\n .then(function(response) {\n isWriting = false;\n if (!response.ok) {\n console.warn('[BrowserLogs] Failed to write log:', response.status);\n }\n // Continue processing next item in queue\n processWriteQueue();\n })\n .catch(function(error) {\n console.warn('[BrowserLogs] Failed to write log:', error.message);\n // On failure, put log back to queue head for retry\n writeQueue.unshift(entry);\n isWriting = false;\n // Retry after delay\n setTimeout(processWriteQueue, 1000);\n });\n }\n \n // Limit headers object size\n function truncateHeaders(headers) {\n if (!headers) return headers;\n var jsonStr = JSON.stringify(headers);\n if (jsonStr.length <= MAX_HEADER_SIZE) return headers;\n return '[Headers truncated, size: ' + jsonStr.length + ']';\n }\n \n // Truncate oversized log entries\n function truncateLogEntry(entry) {\n var jsonStr = JSON.stringify(entry);\n if (jsonStr.length <= MAX_LOG_ENTRY_SIZE) {\n return entry;\n }\n \n // If oversized, progressively truncate non-critical fields\n var truncated = Object.assign({}, entry);\n \n // 1. Truncate response body first\n if (truncated.responseBody && typeof truncated.responseBody === 'string') {\n truncated.responseBody = truncated.responseBody.substring(0, 500) + '... [truncated]';\n }\n \n // 2. Truncate request body\n if (truncated.requestBody && typeof truncated.requestBody === 'string') {\n truncated.requestBody = truncated.requestBody.substring(0, 500) + '... [truncated]';\n }\n \n // 3. Truncate message\n if (truncated.message && typeof truncated.message === 'string' && truncated.message.length > 1000) {\n truncated.message = truncated.message.substring(0, 1000) + '... [truncated]';\n }\n \n // 4. Truncate stack\n if (truncated.stack && Array.isArray(truncated.stack) && truncated.stack.length > 3) {\n truncated.stack = truncated.stack.slice(0, 3);\n }\n \n // Add truncation marker\n truncated._truncated = true;\n truncated._originalSize = jsonStr.length;\n \n return truncated;\n }\n \n // Add log and send immediately (ensure order)\n function addLog(entry) {\n var truncatedEntry = truncateLogEntry(entry);\n writeQueue.push(truncatedEntry);\n processWriteQueue();\n }\n \n // ============================================\n // Console log collection\n // ============================================\n var originalConsole = {\n log: console.log,\n info: console.info,\n warn: console.warn,\n error: console.error,\n debug: console.debug\n };\n \n function getStackTrace() {\n var stack = new Error().stack || '';\n var lines = stack.split('\\\\n').slice(3);\n // Limit stack lines\n return lines.slice(0, MAX_STACK_LINES).map(function(line) { return line.trim(); });\n }\n \n function formatMessage(args) {\n return Array.from(args).map(function(arg) {\n if (arg === null) return 'null';\n if (arg === undefined) return 'undefined';\n if (typeof arg === 'object') {\n try {\n return JSON.stringify(arg);\n } catch (e) {\n return String(arg);\n }\n }\n return String(arg);\n }).join(' ');\n }\n \n function createLogEntry(level, args) {\n return {\n type: 'console',\n timestamp: new Date().toISOString(),\n level: level,\n message: formatMessage(args),\n stack: getStackTrace()\n };\n }\n \n // Check if message should be filtered (contains [vite] text)\n function shouldFilterConsoleLog(args) {\n for (var i = 0; i < args.length; i++) {\n var arg = args[i];\n if (typeof arg === 'string' && arg.indexOf('[vite]') !== -1) {\n return true;\n }\n }\n return false;\n }\n \n function wrapConsoleMethod(method, level) {\n return function() {\n var args = arguments;\n // Filter out logs containing [vite]\n if (shouldFilterConsoleLog(args)) {\n return originalConsole[method].apply(console, args);\n }\n var entry = createLogEntry(level, args);\n addLog(entry);\n return originalConsole[method].apply(console, args);\n };\n }\n \n console.log = wrapConsoleMethod('log', 'log');\n console.info = wrapConsoleMethod('info', 'info');\n console.warn = wrapConsoleMethod('warn', 'warn');\n console.error = wrapConsoleMethod('error', 'error');\n console.debug = wrapConsoleMethod('debug', 'debug');\n \n // ============================================\n // Network request collection (exclude SSE and log API requests)\n // ============================================\n \n var MAX_BODY_SIZE = 2000;\n var MAX_LOG_ENTRY_SIZE = 3000; // Max single log entry length\n var MAX_HEADER_SIZE = 500; // Max single header object length\n var MAX_STACK_LINES = 5; // Max stack lines to keep\n const FILTERED_URLS = ['/__browser__', '/builtin']; // Filter out log API and Vite built-in requests\n \n function isSSERequest(url, headers) {\n var sseUrlPatterns = ['/events', '/sse', '/stream', 'text/event-stream'];\n var urlStr = String(url).toLowerCase();\n for (var i = 0; i < sseUrlPatterns.length; i++) {\n if (urlStr.indexOf(sseUrlPatterns[i]) !== -1) {\n return true;\n }\n }\n \n if (headers) {\n if (typeof headers.get === 'function') {\n var accept = headers.get('Accept') || headers.get('accept');\n if (accept && accept.indexOf('text/event-stream') !== -1) {\n return true;\n }\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n if (key.toLowerCase() === 'accept' && headers[key].indexOf('text/event-stream') !== -1) {\n return true;\n }\n }\n }\n }\n \n return false;\n }\n \n function shouldFilterRequest(url) {\n return FILTERED_URLS.some(function(filteredUrl) {\n return String(url).indexOf(filteredUrl) !== -1;\n });\n }\n \n function formatRequestBody(body) {\n if (!body) return null;\n \n try {\n if (typeof body === 'string') {\n return body.substring(0, MAX_BODY_SIZE);\n }\n if (body instanceof FormData) {\n var formDataObj = {};\n body.forEach(function(value, key) {\n if (value instanceof File) {\n formDataObj[key] = '[File: ' + value.name + ', size: ' + value.size + ']';\n } else {\n formDataObj[key] = String(value).substring(0, 1000);\n }\n });\n return JSON.stringify(formDataObj);\n }\n if (body instanceof Blob) {\n return '[Blob: size=' + body.size + ', type=' + body.type + ']';\n }\n if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return '[Binary: size=' + body.byteLength + ']';\n }\n if (body instanceof URLSearchParams) {\n return body.toString().substring(0, MAX_BODY_SIZE);\n }\n return String(body).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading body: ' + e.message + ']';\n }\n }\n \n function formatResponseBody(response, responseType) {\n if (!response) return null;\n \n try {\n if (responseType === '' || responseType === 'text') {\n return String(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'json') {\n return JSON.stringify(response).substring(0, MAX_BODY_SIZE);\n }\n if (responseType === 'document') {\n return '[Document]';\n }\n if (responseType === 'blob') {\n return '[Blob: size=' + response.size + ']';\n }\n if (responseType === 'arraybuffer') {\n return '[ArrayBuffer: size=' + response.byteLength + ']';\n }\n return String(response).substring(0, MAX_BODY_SIZE);\n } catch (e) {\n return '[Error reading response: ' + e.message + ']';\n }\n }\n \n // Intercept XMLHttpRequest\n var originalXHROpen = XMLHttpRequest.prototype.open;\n var originalXHRSend = XMLHttpRequest.prototype.send;\n var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;\n \n XMLHttpRequest.prototype.open = function(method, url, async, user, password) {\n this.__requestInfo__ = {\n method: method,\n url: url,\n startTime: null,\n headers: {}\n };\n return originalXHROpen.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.setRequestHeader = function(name, value) {\n if (this.__requestInfo__ && this.__requestInfo__.headers) {\n this.__requestInfo__.headers[name] = value;\n }\n return originalXHRSetRequestHeader.apply(this, arguments);\n };\n \n XMLHttpRequest.prototype.send = function(body) {\n var xhr = this;\n var requestInfo = xhr.__requestInfo__;\n \n if (requestInfo) {\n // Skip SSE requests and filtered requests\n if (isSSERequest(requestInfo.url, requestInfo.headers) || shouldFilterRequest(requestInfo.url)) {\n return originalXHRSend.apply(this, arguments);\n }\n \n requestInfo.startTime = Date.now();\n requestInfo.requestBody = formatRequestBody(body);\n \n xhr.addEventListener('loadend', function() {\n var contentType = xhr.getResponseHeader('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return;\n }\n \n var responseHeaders = {};\n var allHeaders = xhr.getAllResponseHeaders();\n if (allHeaders) {\n allHeaders.split('\\\\r\\\\n').forEach(function(line) {\n var parts = line.split(': ');\n if (parts.length === 2) {\n responseHeaders[parts[0]] = parts[1];\n }\n });\n }\n \n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'xhr',\n method: requestInfo.method,\n url: requestInfo.url,\n status: xhr.status,\n statusText: xhr.statusText,\n duration: Date.now() - requestInfo.startTime,\n requestHeaders: truncateHeaders(requestInfo.headers),\n requestBody: requestInfo.requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseType: xhr.responseType,\n responseBody: formatResponseBody(xhr.response, xhr.responseType),\n responseSize: xhr.response ? (typeof xhr.response === 'string' ? xhr.response.length : (xhr.response.byteLength || xhr.response.size || null)) : null\n };\n \n addLog(entry);\n });\n }\n \n return originalXHRSend.apply(this, arguments);\n };\n \n // Intercept Fetch API\n var originalFetch = window.fetch;\n \n function headersToObject(headers) {\n var obj = {};\n if (!headers) return obj;\n \n if (typeof headers.forEach === 'function') {\n headers.forEach(function(value, key) {\n obj[key] = value;\n });\n } else if (typeof headers === 'object') {\n for (var key in headers) {\n obj[key] = headers[key];\n }\n }\n return obj;\n }\n \n window.fetch = function(input, init) {\n var startTime = Date.now();\n var method = (init && init.method) || 'GET';\n var url = typeof input === 'string' ? input : input.url;\n var headers = init && init.headers;\n \n // Skip SSE requests and filtered requests\n if (isSSERequest(url, headers) || shouldFilterRequest(url)) {\n return originalFetch.apply(this, arguments);\n }\n \n var requestHeaders = headersToObject(headers);\n var requestBody = formatRequestBody(init && init.body);\n \n return originalFetch.apply(this, arguments)\n .then(function(response) {\n var contentType = response.headers.get('Content-Type') || '';\n if (contentType.indexOf('text/event-stream') !== -1) {\n return response;\n }\n \n var clonedResponse = response.clone();\n var responseHeaders = headersToObject(response.headers);\n \n clonedResponse.text().then(function(bodyText) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: bodyText ? bodyText.substring(0, MAX_BODY_SIZE) : null,\n responseSize: bodyText ? bodyText.length : null,\n ok: response.ok\n };\n \n addLog(entry);\n }).catch(function(e) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: response.status,\n statusText: response.statusText,\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: truncateHeaders(responseHeaders),\n responseBody: '[Unable to read: ' + e.message + ']',\n responseSize: null,\n ok: response.ok\n };\n \n addLog(entry);\n });\n \n return response;\n })\n .catch(function(error) {\n var entry = {\n type: 'request',\n timestamp: new Date().toISOString(),\n requestType: 'fetch',\n method: method,\n url: url,\n status: 0,\n statusText: 'Network Error',\n duration: Date.now() - startTime,\n requestHeaders: truncateHeaders(requestHeaders),\n requestBody: requestBody,\n responseHeaders: null,\n responseBody: null,\n error: error.message\n };\n \n addLog(entry);\n throw error;\n });\n };\n \n // ============================================\n // Global error capture\n // ============================================\n window.addEventListener('error', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: event.message,\n stack: event.error ? event.error.stack : 'at ' + event.filename + ':' + event.lineno + ':' + event.colno\n };\n addLog(entry);\n });\n \n // ============================================\n // Vite deps 504 error capture using PerformanceObserver\n // Only captures 504 errors for node_modules/.vite resources (pre-bundled dependencies)\n // ============================================\n var reportedUrls = {}; // Track reported URLs to avoid duplicates\n \n if (typeof PerformanceObserver !== 'undefined') {\n var perfObserver = new PerformanceObserver(function(list) {\n var entries = list.getEntries();\n for (var i = 0; i < entries.length; i++) {\n var perfEntry = entries[i];\n // Only check script resources\n if (perfEntry.initiatorType !== 'script') {\n continue;\n }\n \n var resourceUrl = perfEntry.name || '';\n // Only report errors for node_modules/.vite resources\n if (resourceUrl.indexOf('node_modules/.vite') === -1 && resourceUrl.indexOf('/node_modules/.vite') === -1) {\n continue;\n }\n \n // Check if response status is 504 (Gateway Timeout)\n // responseStatus is available in Resource Timing Level 2\n var status = perfEntry.responseStatus;\n if (status === 504) {\n // Avoid duplicate reports\n if (reportedUrls[resourceUrl]) {\n continue;\n }\n reportedUrls[resourceUrl] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: resourceUrl,\n status: 504,\n message: 'Vite pre-bundled dependency returned 504 Gateway Timeout: ' + resourceUrl,\n duration: perfEntry.duration,\n transferSize: perfEntry.transferSize\n };\n addLog(entry);\n }\n }\n });\n \n try {\n perfObserver.observe({ type: 'resource', buffered: true });\n } catch (e) {\n // Fallback for browsers that don't support the options\n try {\n perfObserver.observe({ entryTypes: ['resource'] });\n } catch (e2) {\n originalConsole.warn('[BrowserLogs] PerformanceObserver not supported:', e2.message);\n }\n }\n }\n \n // ============================================\n // Script load error capture (for 504 and other network errors)\n // This captures errors that PerformanceObserver might miss\n // ============================================\n \n // Use MutationObserver to watch for dynamically added script tags\n function attachScriptErrorHandler(script) {\n if (script.__errorHandlerAttached__) return;\n script.__errorHandlerAttached__ = true;\n \n script.addEventListener('error', function(event) {\n var src = script.src || '';\n \n // Only report errors for node_modules/.vite resources\n if (src.indexOf('node_modules/.vite') === -1 && src.indexOf('/node_modules/.vite') === -1) {\n return;\n }\n \n // Avoid duplicate reports\n if (reportedUrls[src]) {\n return;\n }\n reportedUrls[src] = true;\n \n var entry = {\n type: 'vite-deps-error',\n timestamp: new Date().toISOString(),\n level: 'error',\n url: src,\n status: 'load-error',\n message: 'Vite pre-bundled dependency failed to load (possibly 504 Gateway Timeout): ' + src,\n errorType: event.type\n };\n addLog(entry);\n });\n }\n \n // Attach error handlers to existing scripts\n var existingScripts = document.querySelectorAll('script[src]');\n for (var i = 0; i < existingScripts.length; i++) {\n attachScriptErrorHandler(existingScripts[i]);\n }\n \n // Watch for dynamically added scripts\n if (typeof MutationObserver !== 'undefined') {\n var scriptObserver = new MutationObserver(function(mutations) {\n for (var i = 0; i < mutations.length; i++) {\n var mutation = mutations[i];\n for (var j = 0; j < mutation.addedNodes.length; j++) {\n var node = mutation.addedNodes[j];\n if (node.nodeName === 'SCRIPT' && node.src) {\n attachScriptErrorHandler(node);\n }\n // Also check child nodes\n if (node.querySelectorAll) {\n var scripts = node.querySelectorAll('script[src]');\n for (var k = 0; k < scripts.length; k++) {\n attachScriptErrorHandler(scripts[k]);\n }\n }\n }\n }\n });\n \n scriptObserver.observe(document.documentElement, {\n childList: true,\n subtree: true\n });\n }\n \n // Also intercept document.createElement to catch scripts before they're added to DOM\n var originalCreateElement = document.createElement.bind(document);\n document.createElement = function(tagName) {\n var element = originalCreateElement(tagName);\n if (tagName.toLowerCase() === 'script') {\n // Use a setter to catch when src is set\n var originalSrc = '';\n Object.defineProperty(element, '__originalSrc__', {\n get: function() { return originalSrc; },\n set: function(val) { originalSrc = val; }\n });\n \n // Defer attaching error handler until src is set\n var srcDescriptor = Object.getOwnPropertyDescriptor(HTMLScriptElement.prototype, 'src');\n if (srcDescriptor && srcDescriptor.set) {\n var originalSrcSetter = srcDescriptor.set;\n Object.defineProperty(element, 'src', {\n get: function() {\n return srcDescriptor.get ? srcDescriptor.get.call(this) : this.getAttribute('src');\n },\n set: function(value) {\n if (originalSrcSetter) {\n originalSrcSetter.call(this, value);\n } else {\n this.setAttribute('src', value);\n }\n attachScriptErrorHandler(this);\n },\n configurable: true\n });\n }\n }\n return element;\n };\n \n window.addEventListener('unhandledrejection', function(event) {\n var entry = {\n type: 'error',\n timestamp: new Date().toISOString(),\n level: 'error',\n message: 'Unhandled Promise Rejection: ' + (event.reason ? (event.reason.message || String(event.reason)) : 'Unknown'),\n stack: event.reason && event.reason.stack ? event.reason.stack : ''\n };\n addLog(entry);\n });\n \n // ============================================\n // Send remaining logs on page unload\n // ============================================\n window.addEventListener('beforeunload', function() {\n if (writeQueue.length > 0) {\n // Use sendBeacon to ensure logs are sent\n writeQueue.forEach(function(entry) {\n navigator.sendBeacon(LOG_API_PATH, JSON.stringify(entry));\n });\n writeQueue = [];\n }\n });\n \n // ============================================\n // Provide manual flush method\n // ============================================\n window.__flushBrowserLogs__ = function() {\n return new Promise(function(resolve) {\n // Wait for queue to finish processing\n function checkQueue() {\n if (writeQueue.length === 0 && !isWriting) {\n resolve();\n } else {\n setTimeout(checkQueue, 100);\n }\n }\n checkQueue();\n });\n };\n \n // Provide method to get queue status\n window.__getBrowserLogsStatus__ = function() {\n return {\n queueLength: writeQueue.length,\n isWriting: isWriting\n };\n };\n \n originalConsole.log('[BrowserLogs] Log collection started');\n})();\n</script>`;\n\n return {\n name: \"vite-plugin-browser-logs\",\n\n configResolved(config) {\n // Determine log file path: use WORKSPACE_DIR env var (set by PM2/Docker),\n // or find the nearest directory containing package.json from config.root,\n // to ensure browser.log is always at the workspace root level.\n const workspaceDir = process.env.WORKSPACE_DIR;\n if (workspaceDir) {\n logFilePath = path.join(workspaceDir, \"browser.log\");\n } else {\n // Fallback: walk up from config.root to find directory with package.json\n let dir = config.root || process.cwd();\n while (dir !== path.dirname(dir)) {\n if (fs.existsSync(path.join(dir, \"package.json\"))) {\n break;\n }\n dir = path.dirname(dir);\n }\n logFilePath = path.join(dir, \"browser.log\");\n }\n },\n\n configureServer(devServer) {\n // Add log write API\n devServer.middlewares.use((req, res, next) => {\n if (req.url === \"/__browser__\" && req.method === \"POST\") {\n // Get request origin, dynamically set CORS headers to avoid protocol mismatch\n const origin = req.headers.origin || \"*\";\n\n let body = \"\";\n req.on(\"data\", (chunk: Buffer) => {\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n try {\n // Ensure log directory exists\n const logDir = path.dirname(logFilePath);\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n // Append to log file\n fs.appendFileSync(logFilePath, `${body}\\n`, \"utf-8\");\n res.writeHead(200, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: true }));\n } catch (error) {\n console.error(\"[BrowserLogs] Write error:\", error);\n res.writeHead(500, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n });\n res.end(JSON.stringify({ success: false, error: String(error) }));\n }\n });\n } else if (req.url === \"/__browser__\" && req.method === \"OPTIONS\") {\n // Handle CORS preflight request\n const origin = req.headers.origin || \"*\";\n res.writeHead(204, {\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST, OPTIONS\",\n \"Access-Control-Allow-Headers\": \"Content-Type\",\n \"Access-Control-Max-Age\": \"86400\",\n });\n res.end();\n } else if (req.url === \"/__browser__\") {\n const origin = req.headers.origin || \"*\";\n res.writeHead(405, {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": origin,\n });\n res.end(JSON.stringify({ error: \"Method not allowed\" }));\n } else {\n next();\n }\n });\n\n console.log(\"[BrowserLogs] Logs will be written to:\", logFilePath);\n },\n\n transformIndexHtml(html) {\n // Insert script after <head> tag to ensure earliest execution\n return html.replace(/<head([^>]*)>/i, `<head$1>${injectedScript}`);\n },\n };\n}\n","import type { Plugin } from \"vite\";\n\n/**\n * Runtime code that will be injected to replace react/jsx-dev-runtime\n * This code tags DOM elements with source information using refs\n */\nconst devRuntimeCode = `\nimport * as React from \"react\";\nimport * as ReactJSXDevRuntime from \"react/jsx-dev-runtime\";\n\nconst _jsxDEV = ReactJSXDevRuntime.jsxDEV;\nexport const Fragment = ReactJSXDevRuntime.Fragment;\n\nconst SOURCE_KEY = Symbol.for(\"__jsxSource__\");\nconst PROJECT_ROOT = \"\";\n\nconst cleanFileName = (fileName) => {\n if (!fileName) return \"\";\n // Remove project root prefix to get relative path\n if (PROJECT_ROOT && fileName.startsWith(PROJECT_ROOT)) {\n const relative = fileName.slice(PROJECT_ROOT.length);\n return relative.startsWith(\"/\") ? relative.slice(1) : relative;\n }\n return fileName;\n};\n\n// Global map to track elements by source location\nconst sourceElementMap = new Map();\nwindow.sourceElementMap = sourceElementMap;\n\nfunction getSourceKey(sourceInfo) {\n return \\`\\${cleanFileName(sourceInfo.fileName)}:\\${sourceInfo.lineNumber}:\\${sourceInfo.columnNumber}\\`;\n}\n\nfunction unregisterElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n const refs = sourceElementMap.get(key);\n if (refs) {\n for (const ref of refs) {\n if (ref.deref() === node) {\n refs.delete(ref);\n break;\n }\n }\n if (refs.size === 0) {\n sourceElementMap.delete(key);\n }\n }\n}\n\nfunction registerElement(node, sourceInfo) {\n const key = getSourceKey(sourceInfo);\n if (!sourceElementMap.has(key)) {\n sourceElementMap.set(key, new Set());\n }\n sourceElementMap.get(key).add(new WeakRef(node));\n}\n\nfunction getTypeName(type) {\n if (typeof type === \"string\") return type;\n if (typeof type === \"function\") return type.displayName || type.name || \"Unknown\";\n if (typeof type === \"object\" && type !== null) {\n return type.displayName || type.render?.displayName || type.render?.name || \"Unknown\";\n }\n return \"Unknown\";\n}\n\nexport function jsxDEV(type, props, key, isStatic, source, self) {\n // For custom components, tag their rendered output\n if (source?.fileName && typeof type !== \"string\" && type !== Fragment) {\n const typeName = getTypeName(type);\n const jsxSourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: typeName,\n };\n\n const originalRef = props?.ref;\n \n // Check if component can safely receive refs\n // - forwardRef components have $$typeof symbol\n // - Class components have prototype.isReactComponent\n // - If there's already a ref, the component expects it\n const isForwardRef = type.$$typeof === Symbol.for('react.forward_ref');\n const isClassComponent = typeof type === 'function' && type.prototype?.isReactComponent;\n const hasExistingRef = originalRef !== undefined;\n \n const canReceiveRef = isForwardRef || isClassComponent || hasExistingRef;\n \n if (canReceiveRef) {\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n if (!node[SOURCE_KEY]) {\n node[SOURCE_KEY] = jsxSourceInfo;\n registerElement(node, jsxSourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n }\n\n // For host elements (div, span, etc.), tag with source info\n if (source?.fileName && typeof type === \"string\") {\n const sourceInfo = {\n fileName: cleanFileName(source.fileName),\n lineNumber: source.lineNumber,\n columnNumber: source.columnNumber,\n displayName: type,\n };\n\n const originalRef = props?.ref;\n\n const enhancedProps = {\n ...props,\n ref: (node) => {\n if (node) {\n const existingSource = node[SOURCE_KEY];\n if (existingSource) {\n if (getSourceKey(existingSource) !== getSourceKey(sourceInfo)) {\n unregisterElement(node, existingSource);\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n } else {\n node[SOURCE_KEY] = sourceInfo;\n registerElement(node, sourceInfo);\n }\n }\n if (typeof originalRef === \"function\") {\n originalRef(node);\n } else if (originalRef && typeof originalRef === \"object\") {\n originalRef.current = node;\n }\n },\n };\n return _jsxDEV(type, enhancedProps, key, isStatic, source, self);\n }\n\n return _jsxDEV(type, props, key, isStatic, source, self);\n}\n`;\n\n/**\n * Vite plugin: JSX Source Tagger\n * Intercepts react/jsx-dev-runtime to add source information to DOM elements\n * Only enabled in development mode\n */\nexport function jsxSourceTaggerPlugin(): Plugin {\n let isDev = false;\n let projectRoot = \"\";\n\n return {\n name: \"vite-plugin-jsx-source-tagger\",\n enforce: \"pre\",\n\n configResolved(config) {\n isDev = config.command === \"serve\";\n projectRoot = config.root;\n },\n\n resolveId(id, importer) {\n if (!isDev) return null;\n\n // Intercept react/jsx-dev-runtime imports\n if (id === \"react/jsx-dev-runtime\" && !importer?.includes(\"\\0jsx-source\")) {\n return \"\\0jsx-source/jsx-dev-runtime\";\n }\n return null;\n },\n\n load(id) {\n if (!isDev) return null;\n\n // Return our custom runtime code with injected projectRoot\n if (id === \"\\0jsx-source/jsx-dev-runtime\") {\n return devRuntimeCode.replace(\n 'const PROJECT_ROOT = \"\";',\n `const PROJECT_ROOT = ${JSON.stringify(projectRoot)};`\n );\n }\n return null;\n },\n };\n}\n","import type { Plugin } from \"vite\";\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport * as esbuild from \"esbuild\";\nimport { Buffer } from \"buffer\";\n\n/**\n * Vite plugin: Tailwind Config Sync\n * Generates a JSON file from tailwind.config.ts for runtime access\n * Only enabled in development mode\n */\nexport function tailwindConfigSyncPlugin(options?: { configPath?: string }): Plugin {\n let projectRoot = \"\";\n let isDev = false;\n let cachedConfig: Record<string, unknown> | null = null;\n\n const configPath = options?.configPath || \"./tailwind.config.ts\";\n const VIRTUAL_MODULE_ID = \"@amaster/tailwind-config\";\n const RESOLVED_VIRTUAL_MODULE_ID = \"\\0\" + VIRTUAL_MODULE_ID;\n\n const findConfigFile = async (): Promise<string | null> => {\n const configFile = path.resolve(projectRoot, configPath);\n\n try {\n await fs.access(configFile);\n return configFile;\n } catch {\n // If specified config doesn't exist, try alternative extensions\n if (configPath.endsWith(\".ts\")) {\n const jsConfig = configFile.replace(/\\.ts$/, \".js\");\n try {\n await fs.access(jsConfig);\n return jsConfig;\n } catch {\n return null;\n }\n } else if (configPath.endsWith(\".js\")) {\n const tsConfig = configFile.replace(/\\.js$/, \".ts\");\n try {\n await fs.access(tsConfig);\n return tsConfig;\n } catch {\n return null;\n }\n }\n return null;\n }\n };\n\n const generateConfig = async (): Promise<Record<string, unknown> | null> => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (!tailwindInputFile) return null;\n\n const sourceCode = await fs.readFile(tailwindInputFile, \"utf-8\");\n const result = await esbuild.transform(sourceCode, {\n loader: tailwindInputFile.endsWith(\".ts\") ? \"ts\" : \"js\",\n format: \"esm\",\n platform: \"node\",\n });\n\n const dataUrl = `data:text/javascript;base64,${Buffer.from(result.code).toString(\"base64\")}`;\n const userConfig = await import(dataUrl);\n\n if (!userConfig?.default) {\n throw new Error(\"Invalid Tailwind config structure\");\n }\n\n // Try to resolve with tailwindcss, fallback to raw config\n try {\n const resolveConfig = (await import(\"tailwindcss/resolveConfig.js\")).default;\n cachedConfig = resolveConfig(userConfig.default);\n } catch {\n cachedConfig = userConfig.default;\n }\n\n return cachedConfig;\n } catch {\n return null;\n }\n };\n\n return {\n name: \"vite-plugin-tailwind-config-sync\",\n\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n isDev = resolvedConfig.command === \"serve\";\n },\n\n async buildStart() {\n if (!isDev) return;\n await generateConfig();\n },\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return RESOLVED_VIRTUAL_MODULE_ID;\n }\n },\n\n async load(id) {\n if (id === RESOLVED_VIRTUAL_MODULE_ID) {\n if (!cachedConfig) {\n await generateConfig();\n }\n\n // Generate code with HMR support\n const code = `\nlet config = ${JSON.stringify(cachedConfig)};\n\nlet _updateConfig;\nif (import.meta.hot) {\n // Accept self updates\n import.meta.hot.accept((newModule) => {\n if (newModule && _updateConfig) {\n _updateConfig(newModule.default);\n }\n });\n}\n\nexport default new Proxy(config, {\n get(target, prop) {\n if (prop === 'then') return undefined;\n if (prop === '__setUpdater') {\n return (fn) => { _updateConfig = fn; };\n }\n return target[prop];\n }\n});\n`;\n return code;\n }\n },\n\n configureServer(server) {\n if (!isDev) return;\n\n (async () => {\n try {\n const tailwindInputFile = await findConfigFile();\n if (tailwindInputFile) {\n server.watcher.add(tailwindInputFile);\n }\n } catch {\n // Ignore errors\n }\n })();\n },\n\n async handleHotUpdate({ file, server }) {\n const tailwindInputFile = await findConfigFile();\n\n if (!tailwindInputFile || path.normalize(file) !== path.normalize(tailwindInputFile)) {\n return;\n }\n\n await generateConfig();\n\n const mod = server.moduleGraph.getModuleById(RESOLVED_VIRTUAL_MODULE_ID);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n return [mod];\n }\n\n return [];\n },\n };\n}\n","import type { Plugin } from 'vite';\n\nexport interface TaroStyleAdapterOptions {\n /**\n * Design width for responsive scaling (default: 375)\n * Should match Taro config's designWidth\n */\n designWidth?: number;\n \n /**\n * Maximum viewport width to scale (default: 750)\n * Beyond this width, font-size stays fixed\n */\n maxWidth?: number;\n\n /**\n * Base font size in pixels (default: 12)\n * Should match Taro config's baseFontSize\n */\n baseFontSize?: number;\n\n /**\n * Minimum root font size in pixels (default: 12)\n * Should match Taro config's minRootSize\n */\n minRootSize?: number;\n\n /**\n * Maximum root font size in pixels (default: 24)\n * Should match Taro config's maxRootSize\n */\n maxRootSize?: number;\n}\n\n/**\n * Taro H5 样式适配插件\n * \n * 功能:\n * 1. 动态计算根字号,使 H5 的 rem 与小程序的 rpx 行为对齐\n * 2. 隐藏 Taro 页面容器的滚动条,用于编辑器 iframe 预览\n * \n * 原理:\n * - 小程序 rpx: 1rpx = 屏幕宽度 / 750\n * - H5 rem: Taro 把 rpx 转成 rem,基于 baseFontSize\n * - 本插件动态设置 html font-size,使 rem 的实际像素值与 rpx 对齐\n * \n * 注意:此插件会覆盖 Taro 默认注入的根字号脚本,配置需与 Taro pxtransform 保持一致\n * \n * @example\n * ```ts\n * // In Taro config/dev.ts\n * import { taroStyleAdapterPlugin } from '@amaster.ai/vite-plugins'\n * \n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [\n * taroStyleAdapterPlugin({ \n * designWidth: 375,\n * baseFontSize: 12,\n * minRootSize: 12,\n * maxRootSize: 24\n * })\n * ]\n * }\n * }\n * ```\n */\nexport function taroStyleAdapterPlugin(options: TaroStyleAdapterOptions = {}): Plugin {\n const { \n designWidth = 375, \n maxWidth = 750,\n baseFontSize = 12,\n minRootSize = 12,\n maxRootSize = 24\n } = options;\n \n return {\n name: 'vite-plugin-taro-style-adapter',\n apply: 'serve', // 仅在开发模式下生效\n transformIndexHtml(html) {\n // 动态根字号脚本\n // 公式:fontSize = (clientWidth / designWidth) * baseFontSize\n // 当 designWidth=375, baseFontSize=12 时:\n // - 375px 屏幕 → 12px (1rem = 12px)\n // - 750px 屏幕 → 24px (1rem = 24px)\n // 这样 rem 值在不同屏幕宽度下的视觉比例与小程序 rpx 一致\n const flexibleScript = `\n<script data-taro-flexible=\"true\">\n(function() {\n var designWidth = ${designWidth};\n var maxWidth = ${maxWidth};\n var baseFontSize = ${baseFontSize};\n var minRootSize = ${minRootSize};\n var maxRootSize = ${maxRootSize};\n \n function setRootFontSize() {\n var docEl = document.documentElement;\n var clientWidth = docEl.clientWidth;\n \n // 限制最大宽度\n if (clientWidth > maxWidth) {\n clientWidth = maxWidth;\n }\n \n // 计算根字号: (屏幕宽度 / 设计稿宽度) * 基准字号\n var fontSize = (clientWidth / designWidth) * baseFontSize;\n \n // 应用最小/最大限制\n if (fontSize < minRootSize) {\n fontSize = minRootSize;\n } else if (fontSize > maxRootSize) {\n fontSize = maxRootSize;\n }\n \n docEl.style.fontSize = fontSize + 'px';\n }\n \n setRootFontSize();\n \n // 监听窗口变化\n window.addEventListener('resize', setRootFontSize);\n window.addEventListener('orientationchange', setRootFontSize);\n \n // 页面显示时重新计算(解决某些浏览器的 bug)\n document.addEventListener('DOMContentLoaded', setRootFontSize);\n})();\n</script>\n`;\n\n // 滚动条隐藏样式 + Taro Image 组件修复\n const styles = `\n<style data-taro-adapter=\"true\">\n /* 仅 H5 生效:隐藏 Taro 页面容器滚动条,但仍可滚动 */\n .taro_page {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro_page::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /* 隐藏 Taro ScrollView 组件的滚动条 */\n .taro-scroll-view__scroll-y,\n .taro-scroll-view__scroll-x {\n -ms-overflow-style: none; /* IE/Edge 老版 */\n scrollbar-width: none; /* Firefox */\n }\n\n .taro-scroll-view__scroll-y::-webkit-scrollbar,\n .taro-scroll-view__scroll-x::-webkit-scrollbar {\n width: 0;\n height: 0;\n display: none; /* Chrome/Safari */\n }\n\n /*\n * 修复 Taro Image 组件在 H5 下的尺寸问题\n * \n * 问题:Taro Image 组件使用 aspectFit 模式时,内部 img 使用 max-width/max-height: 100%\n * 导致小尺寸图片(如 SVG 图标)无法按指定尺寸显示,只显示原始尺寸\n * \n * 解决:让 img 填满 taro-image-core 容器,由容器控制尺寸\n */\n taro-image-core img.taro-img__mode-aspectfit {\n width: 100%;\n height: 100%;\n max-width: none;\n max-height: none;\n position: static;\n transform: none;\n object-fit: contain;\n }\n</style>\n`;\n \n // 在 </head> 之前插入脚本和样式\n return html.replace('</head>', `${flexibleScript}${styles}</head>`);\n }\n };\n}\n","/**\n * PostCSS 插件:H5 模式下将 rpx 预转换为 px\n *\n * 问题背景:\n * - Taro 的 pxtransform 在 H5 模式下会处理 rpx,但它把 rpx 值直接除以 rootValue\n * - 导致 96rpx 被转成 8rem(96/12),实际显示为 96px\n * - 而正确应该是:96rpx = 48px = 4rem = 48px\n *\n * 解决方案:\n * - 在 pxtransform 之前,先把 rpx 转成 px(rpx / 2)\n * - 然后 pxtransform 会正确地把 px 转成 rem(px / 12)\n *\n * 转换链路:96rpx → 48px → 4rem → 48px(正确)\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { rpx2pxPlugin } from '@amaster.ai/vite-plugins'\n * \n * // 在 postcss-config-loader-plugin 中使用\n * {\n * name: 'postcss-config-loader-plugin',\n * config(config) {\n * if (typeof config.css?.postcss === 'object') {\n * config.css?.postcss.plugins?.unshift(tailwindcss())\n * // H5 模式下添加 rpx2px 插件\n * if (process.env.TARO_ENV === 'h5') {\n * config.css?.postcss.plugins?.unshift(rpx2pxPlugin())\n * }\n * }\n * }\n * }\n * ```\n */\n\nexport interface Rpx2pxPluginOptions {\n /**\n * rpx 到 px 的转换比例(默认 2)\n * 即 1rpx = 1/ratio px\n * 默认值 2 表示 2rpx = 1px(基于 375 设计稿)\n */\n ratio?: number;\n}\n\ninterface PostCSSDeclaration {\n value: string;\n}\n\ninterface PostCSSPlugin {\n postcssPlugin: string;\n Declaration: (decl: PostCSSDeclaration) => void;\n}\n\ntype PostCSSPluginCreator = {\n (): PostCSSPlugin;\n postcss: boolean;\n};\n\nexport function rpx2pxPlugin(options: Rpx2pxPluginOptions = {}): PostCSSPlugin {\n const { ratio = 2 } = options;\n \n return {\n postcssPlugin: 'postcss-rpx2px',\n Declaration(decl: PostCSSDeclaration) {\n if (decl.value.includes('rpx')) {\n decl.value = decl.value.replace(/(-?\\d*\\.?\\d+)rpx/gi, (_match: string, num: string) => {\n const pxValue = parseFloat(num) / ratio;\n return pxValue === 0 ? '0' : `${pxValue}px`;\n });\n }\n }\n };\n}\n\n// PostCSS 插件标识\n(rpx2pxPlugin as PostCSSPluginCreator).postcss = true;\n","/**\n * Taro Environment Variables Injection Helper\n * \n * Automatically injects environment variables into Taro's defineConstants\n * so that they will be replaced at build time.\n * \n * @example\n * ```ts\n * // In Taro config/index.ts\n * import { injectTaroEnv } from '@amaster.ai/vite-plugins/taro-env-inject'\n * \n * export default defineConfig({\n * defineConstants: {\n * ...injectTaroEnv()\n * }\n * })\n * ```\n */\n\nexport interface TaroEnvInjectOptions {\n /**\n * Additional environment variable names to inject\n * @default []\n */\n additional?: string[];\n \n /**\n * Whether to inject all TARO_APP_* prefixed variables\n * @default true\n */\n autoInjectTaroApp?: boolean;\n \n /**\n * Whether to inject all VITE_* prefixed variables\n * @default true\n */\n autoInjectVite?: boolean;\n}\n\n/**\n * Inject environment variables into Taro's defineConstants\n * \n * This function reads environment variables and formats them for Taro's defineConstants.\n * Taro will replace these at build time, converting `process.env.XXX` to actual values.\n */\nexport function injectTaroEnv(options: TaroEnvInjectOptions = {}): Record<string, string> {\n const {\n additional = [],\n autoInjectTaroApp = true,\n autoInjectVite = true,\n } = options;\n\n const constants: Record<string, string> = {};\n\n // Collect variable names to inject\n const varsToInject = new Set<string>(additional);\n\n // Auto-detect TARO_APP_* variables\n if (autoInjectTaroApp) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('TARO_APP_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Auto-detect VITE_* variables\n if (autoInjectVite) {\n Object.keys(process.env).forEach(key => {\n if (key.startsWith('VITE_')) {\n varsToInject.add(key);\n }\n });\n }\n\n // Inject variables into defineConstants format\n varsToInject.forEach(varName => {\n const value = process.env[varName] || '';\n constants[`process.env.${varName}`] = JSON.stringify(value);\n });\n\n return constants;\n}\n\n/**\n * Inject specific environment variables for amaster.ai mini-program builds\n * \n * This is a convenience function that injects the standard environment variables\n * used by @amaster.ai/http-client for API base URL configuration.\n */\nexport function injectAmasterEnv(): Record<string, string> {\n return {\n 'process.env.TARO_APP_API_BASE_URL': JSON.stringify(process.env.TARO_APP_API_BASE_URL || ''),\n 'process.env.VITE_API_BASE_URL': JSON.stringify(process.env.VITE_API_BASE_URL || ''),\n };\n}\n","import { editorBridgePlugin } from \"./editor-bridge\";\nimport { routesExposePlugin } from \"./routes-expose\";\nimport { browserLogsPlugin } from \"./browser-logs\";\nimport { jsxSourceTaggerPlugin } from \"./tagger\";\nimport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n// import { smartReloadPlugin } from \"./smart-reload\"; // 智能重载功能开发中,暂不启用\nimport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\nimport { rpx2pxPlugin } from \"./postcss-rpx2px\";\nimport process from \"node:process\";\nimport type { Plugin } from \"vite\";\n\nexport interface DevToolsOptions {\n /**\n * 是否为 Taro 项目\n * - true: 启用 Taro 相关插件(taroStyleAdapterPlugin、rpx2pxPlugin)\n * - false: 禁用 Taro 相关插件\n * - undefined: 自动检测(通过 process.env.TARO_ENV 判断,默认为 false)\n */\n isTaro?: boolean;\n\n /**\n * Taro style adapter options\n * Controls H5 responsive scaling to match mini-program rpx behavior\n * 仅在 isTaro 为 true 时生效\n */\n styleAdapter?: TaroStyleAdapterOptions;\n\n /**\n * 是否启用 JSX Source Tagger(通过 Symbol 标记元素源码位置)\n * 默认:开发模式启用\n */\n jsxSourceTagger?: boolean;\n\n /**\n * 是否启用 Tailwind Config 同步(生成 JSON 文件)\n * 默认:开发模式启用\n */\n tailwindConfigSync?: boolean;\n\n /**\n * Tailwind 配置文件路径\n * 默认:./tailwind.config.ts\n */\n tailwindConfigPath?: string;\n}\n\n/**\n * 开发工具插件集合,简化调用,vite.config.ts 直接 devTools() 即可\n *\n * @param options 配置项\n * @param options.isTaro 是否为 Taro 项目(默认根据 TARO_ENV 自动判断)\n * @param options.styleAdapter Taro H5 样式适配配置,designWidth 应与 Taro config 一致\n * @returns Plugin[] Vite 插件数组\n *\n * @example\n * ```ts\n * // Taro 项目 - config/dev.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * compiler: {\n * type: 'vite',\n * vitePlugins: [devTools({ isTaro: true })]\n * }\n * }\n * ```\n *\n * @example\n * ```ts\n * // React 项目 - vite.config.ts\n * import devTools from \"@amaster.ai/vite-plugins\";\n *\n * export default {\n * plugins: [devTools()] // isTaro 默认为 false\n * }\n * ```\n */\nexport default function devTools(options: DevToolsOptions = {}): Plugin[] {\n // 判断是否为 Taro 项目\n // 优先使用用户显式配置,否则通过环境变量判断\n const isTaro = options.isTaro ?? process.env.TARO_ENV === \"h5\";\n\n const plugins: Plugin[] = [\n // componentIdPlugin(), // 暂不启用\n editorBridgePlugin(),\n routesExposePlugin(),\n // smartReloadPlugin() // 智能重载:拦截 full-reload,静默等待重连\n ];\n\n // JSX Source Tagger - 默认开发模式启用\n if (options.jsxSourceTagger !== false) {\n plugins.push(jsxSourceTaggerPlugin());\n }\n\n // Tailwind Config Sync - 默认开发模式启用\n if (options.tailwindConfigSync !== false) {\n plugins.push(\n tailwindConfigSyncPlugin({\n configPath: options.tailwindConfigPath,\n })\n );\n }\n\n // 仅在 Taro 项目中添加 Taro 相关插件\n if (isTaro) {\n // Taro H5 样式适配(运行时)\n plugins.unshift(taroStyleAdapterPlugin(options.styleAdapter));\n\n // H5 开发模式下添加 rpx2px PostCSS 插件(编译时)\n plugins.unshift({\n name: \"dev-postcss-rpx2px-plugin\",\n apply: \"serve\",\n config(config) {\n if (typeof config.css?.postcss === \"object\") {\n // 在最前面插入,确保在 pxtransform 之前执行\n config.css?.postcss.plugins?.unshift(rpx2pxPlugin());\n }\n },\n });\n }\n\n // process.env.WORKSPACE_GIT_REPO 有这个表示是在 sandbox 里面运行,启用浏览器日志插件\n if (process.env.WORKSPACE_GIT_REPO) {\n plugins.push(browserLogsPlugin());\n }\n\n return plugins;\n}\n\nexport {\n editorBridgePlugin,\n routesExposePlugin,\n // smartReloadPlugin\n};\n\n// Export Taro environment injection helpers\nexport { injectTaroEnv, injectAmasterEnv } from \"./taro-env-inject\";\n\n// Export Taro style adapter plugin and its types\nexport { taroStyleAdapterPlugin, type TaroStyleAdapterOptions } from \"./taro-style-adapter\";\n\n// Export PostCSS rpx2px plugin for H5 mode\nexport { rpx2pxPlugin, type Rpx2pxPluginOptions } from \"./postcss-rpx2px\";\n\n// Export tagger and tailwind config sync plugins\nexport { jsxSourceTaggerPlugin } from \"./tagger\";\nexport { tailwindConfigSyncPlugin } from \"./tailwind-config-sync\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/vite-plugins",
3
- "version": "1.0.0-beta.44",
3
+ "version": "1.0.0-beta.46",
4
4
  "description": "Collection of Vite plugins for React applications",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",