makelabs
Version:
Component tagging toolkit for visual editing
1 lines • 7.46 kB
JavaScript
import e from"path";import{existsSync as r}from"fs";function findProjectRoot(t=process.cwd()){try{let a=t,o=0;for(;a!==e.parse(a).root&&o<20;){if(r(e.join(a,"package.json")))return a;a=e.dirname(a),o++}return process.cwd()}catch(e){return console.error("Error finding project root:",e),process.cwd()}}var t=["object3D","audioListener","positionalAudio","mesh","batchedMesh","instancedMesh","scene","sprite","lOD","skinnedMesh","skeleton","bone","lineSegments","lineLoop","points","group","camera","perspectiveCamera","orthographicCamera","cubeCamera","arrayCamera","instancedBufferGeometry","bufferGeometry","boxBufferGeometry","circleBufferGeometry","coneBufferGeometry","cylinderBufferGeometry","dodecahedronBufferGeometry","extrudeBufferGeometry","icosahedronBufferGeometry","latheBufferGeometry","octahedronBufferGeometry","planeBufferGeometry","polyhedronBufferGeometry","ringBufferGeometry","shapeBufferGeometry","sphereBufferGeometry","tetrahedronBufferGeometry","torusBufferGeometry","torusKnotBufferGeometry","tubeBufferGeometry","wireframeGeometry","tetrahedronGeometry","octahedronGeometry","icosahedronGeometry","dodecahedronGeometry","polyhedronGeometry","tubeGeometry","torusKnotGeometry","torusGeometry","sphereGeometry","ringGeometry","planeGeometry","latheGeometry","shapeGeometry","extrudeGeometry","edgesGeometry","coneGeometry","cylinderGeometry","circleGeometry","boxGeometry","capsuleGeometry","material","shadowMaterial","spriteMaterial","rawShaderMaterial","shaderMaterial","pointsMaterial","meshPhysicalMaterial","meshStandardMaterial","meshPhongMaterial","meshToonMaterial","meshNormalMaterial","meshLambertMaterial","meshDepthMaterial","meshDistanceMaterial","meshBasicMaterial","meshMatcapMaterial","lineDashedMaterial","lineBasicMaterial","primitive","light","spotLightShadow","spotLight","pointLight","rectAreaLight","hemisphereLight","directionalLightShadow","directionalLight","ambientLight","lightShadow","ambientLightProbe","hemisphereLightProbe","lightProbe","texture","videoTexture","dataTexture","dataTexture3D","compressedTexture","cubeTexture","canvasTexture","depthTexture","raycaster","vector2","vector3","vector4","euler","matrix3","matrix4","quaternion","bufferAttribute","color","fog","fogExp2","shape"],a=["AsciiRenderer","Billboard","Clone","ComputedAttribute","Decal","Edges","Effects","GradientTexture","Image","MarchingCubes","Outlines","PositionalAudio","Sampler","ScreenSizer","ScreenSpace","Splat","Svg","Text","Text3D","Trail","CubeCamera","OrthographicCamera","PerspectiveCamera","CameraControls","FaceControls","KeyboardControls","MotionPathControls","PresentationControls","ScrollControls","DragControls","GizmoHelper","Grid","Helper","PivotControls","TransformControls","CubeTexture","Fbx","Gltf","Ktx2","Loader","Progress","ScreenVideoTexture","Texture","TrailTexture","VideoTexture","WebcamVideoTexture","CycleRaycast","DetectGPU","Example","FaceLandmarker","Fbo","Html","Select","SpriteAnimator","StatsGl","Stats","Trail","Wireframe","CurveModifier","AdaptiveDpr","AdaptiveEvents","BakeShadows","Bvh","Detailed","Instances","Merged","meshBounds","PerformanceMonitor","Points","Preload","Segments","Fisheye","Hud","Mask","MeshPortalMaterial","RenderCubeTexture","RenderTexture","View","MeshDiscardMaterial","MeshDistortMaterial","MeshReflectorMaterial","MeshRefractionMaterial","MeshTransmissionMaterial","MeshWobbleMaterial","PointMaterial","shaderMaterial","SoftShadows","CatmullRomLine","CubicBezierLine","Facemesh","Line","Mesh","QuadraticBezierLine","RoundedBox","ScreenQuad","AccumulativeShadows","Backdrop","BBAnchor","Bounds","CameraShake","Caustics","Center","Cloud","ContactShadows","Environment","Float","Lightformer","MatcapTexture","NormalTexture","RandomizedLight","Resize","ShadowAlpha","Shadow","Sky","Sparkles","SpotLightShadow","SpotLight","Stage","Stars","OrbitControls"];function shouldTagElement(e,r={}){const{excludeElements:o=["Fragment","React.Fragment"],excludeThreeFiber:i=!0,excludeDrei:n=!0,customExcludes:s=[]}=r;return!o.includes(e)&&(!s.includes(e)&&((!i||!t.includes(e))&&(!n||!a.includes(e))))}import{parse as o}from"@babel/parser";import*as i from"esbuild";import n from"fs/promises";import s from"magic-string";import l from"path";import c from"tailwindcss/resolveConfig.js";var m=new Set([".jsx",".tsx"]);function d(e={}){const r={include:[".jsx",".tsx"],excludeElements:["Fragment","React.Fragment"],excludeThreeFiber:!0,excludeDrei:!0,customExcludes:[],generateTailwindConfig:!1,tailwindConfigPath:"./tailwind.config.ts",tailwindOutputPath:"./src/tailwind.config.ml.json",...e},t=findProjectRoot(),a=process.cwd(),d={totalFiles:0,processedFiles:0,totalElements:0},u=l.resolve(t,r.tailwindConfigPath),p=l.resolve(t,r.tailwindOutputPath),h=l.resolve(t,"./.ml.tailwind.config.js");return{name:"makelabs-visual-editor-plugin",enforce:"pre",async transform(e,t){if(!m.has(l.extname(t))||t.includes("node_modules"))return null;d.totalFiles++;const i=l.relative(a,t);try{const a=o(e,{sourceType:"module",plugins:["jsx","typescript"]}),n=new s(e);let c=0,m=null;const{walk:u}=await import("estree-walker");return u(a,{enter(e){if("JSXElement"===e.type&&(m=e),"JSXOpeningElement"===e.type){const a=e;let o;if("JSXIdentifier"===a.name.type)o=a.name.name;else{if("JSXMemberExpression"!==a.name.type)return;{const e=a.name;o=`${e.object.name}.${e.property.name}`}}if(!shouldTagElement(o,r))return;const s=a.attributes.reduce((e,r)=>("JSXAttribute"===r.type&&("StringLiteral"===r.value?.type?e[r.name.name]=r.value.value:"JSXExpressionContainer"===r.value?.type&&"StringLiteral"===r.value.expression?.type&&(e[r.name.name]=r.value.expression.value)),e),{});let d="";m&&m.children&&(d=m.children.map(e=>"JSXText"===e.type?e.value.trim():"JSXExpressionContainer"===e.type&&"StringLiteral"===e.expression?.type?e.expression.value:"").filter(Boolean).join(" ").trim());const u={};d&&(u.text=d),s.placeholder&&(u.placeholder=s.placeholder),s.className&&(u.className=s.className);const p=a.loc?.start?.line??0,h=a.loc?.start?.column??0,f=`${i}:${p}:${h}`,y=l.basename(t),g=[`data-ml-id="${f}"`,`data-ml-name="${o}"`,[`data-component-path="${i}"`,`data-component-line="${p}"`,`data-component-file="${y}"`,`data-component-name="${o}"`,`data-component-content="${encodeURIComponent(JSON.stringify(u))}"`].join(" ")].join(" ");n.appendLeft(a.name.end??0,` ${g}`),c++}}}),d.processedFiles++,d.totalElements+=c,{code:n.toString(),map:n.generateMap({hires:!0})}}catch(e){return console.error(`MakeLabs: Error processing file ${i}:`,e),d.processedFiles++,null}},async buildStart(){if(r.generateTailwindConfig)try{await f()}catch(e){console.error("MakeLabs: Error generating tailwind config:",e)}},configureServer(e){if(r.generateTailwindConfig)try{e.watcher.add(u),e.watcher.on("change",async e=>{l.normalize(e)===l.normalize(u)&&await f()})}catch(e){console.error("MakeLabs: Error adding watcher:",e)}},buildEnd(){d.totalElements,d.processedFiles}};async function f(){try{await i.build({entryPoints:[u],outfile:h,bundle:!0,format:"esm",banner:{js:'import { createRequire } from "module"; const _0 = createRequire(import.meta.url);'}});const e=await import(h+"?update="+Date.now());if(!e||!e.default)throw new Error("Invalid Tailwind config structure");const r=c(e.default);await n.writeFile(p,JSON.stringify(r,null,2)),await n.unlink(h).catch(()=>{})}catch(e){throw console.error("MakeLabs: Error in generateTailwindConfig:",e),e}}}export{findProjectRoot,shouldTagElement,d as viteTagger};