@dhiwise/component-tagger
Version:
Automatically annotate JSX components and HTML elements with data attributes
5 lines (4 loc) • 8.38 kB
JavaScript
import{createUnplugin as K}from"unplugin";import*as b from"path";import{parse as V}from"@babel/parser";import{traverse as q}from"@babel/core";import W from"magic-string";import H from"picomatch";var L=new Set(["Fragment","Suspense","StrictMode","Profiler","React.Fragment"]),J=["three","@react-three/fiber","@react-three/drei","@react-three/rapier","@react-three/a11y","@react-three/csg","@react-three/flex","@react-three/gpu-pathtracer","@react-three/postprocessing","@react-three/cannon","@react-three/xr","@react-three/test-renderer","three/addons","three/examples"],$=["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","spotLightHelper","skeletonHelper","pointLightHelper","hemisphereLightHelper","gridHelper","polarGridHelper","directionalLightHelper","cameraHelper","boxHelper","box3Helper","planeHelper","arrowHelper","axesHelper","texture","videoTexture","dataTexture","dataTexture3D","compressedTexture","cubeTexture","canvasTexture","depthTexture","raycaster","vector2","vector3","vector4","euler","matrix3","matrix4","quaternion","bufferAttribute","float16BufferAttribute","float32BufferAttribute","float64BufferAttribute","int8BufferAttribute","int16BufferAttribute","int32BufferAttribute","uint8BufferAttribute","uint16BufferAttribute","uint32BufferAttribute","instancedBufferAttribute","color","fog","fogExp2","shape","colorShiftMaterial"];var u={red:e=>`\x1B[31m${e}\x1B[0m`,green:e=>`\x1B[32m${e}\x1B[0m`,yellow:e=>`\x1B[33m${e}\x1B[0m`,blue:e=>`\x1B[34m${e}\x1B[0m`,cyan:e=>`\x1B[36m${e}\x1B[0m`};function A(e){let t=new Set;for(let r of e.program.body)if(r.type==="ImportDeclaration"){let o=r,i=o.source.value;if(J.some(n=>i===n||i.startsWith(n+"/")))for(let n of o.specifiers)n.type==="ImportSpecifier"||n.type==="ImportDefaultSpecifier"?t.add(n.local.name):n.type==="ImportNamespaceSpecifier"&&t.add(`${n.local.name}.*`)}return t}var M=new Map;function N(e){let t=e.sort().join(",");if(!M.has(t)){let r=e.map(i=>`**/*${i}`),o=H(r);M.set(t,o)}return M.get(t)}function x(e,t){let r=t.extensions||[".jsx",".tsx",".js",".ts"];return N(r)(e)?![".test.",".spec.","__tests__","__mocks__"].some(n=>e.includes(n)):!1}function B(e,t,r){return t.includeElements&&t.includeElements.length>0?t.includeElements.includes(e):t.shouldTag?t.shouldTag(e):!(t.excludeElements&&t.excludeElements.includes(e)||L.has(e)||r&&j(e,r))}function j(e,t){if(t.has(e)||$.includes(e))return!0;for(let r of t)if(r.endsWith(".*")){let o=r.slice(0,-2);if(e.startsWith(`${o}.`))return!0}return!1}function k(e){if(e){if(e.type==="StringLiteral")return e.value;if(e.type==="JSXExpressionContainer"){let t=e.expression;if(t.type==="StringLiteral")return t.value;if(t.type==="TemplateLiteral"&&t.quasis.length===1)return t.quasis[0].value.raw;if(t.type==="BinaryExpression"&&t.operator==="+"){let r=t.left.type==="StringLiteral"?t.left.value:"",o=t.right.type==="StringLiteral"?t.right.value:"";return r+o}if(t.type==="Identifier")return`[var:${t.name}]`}}}function _(e,t,r){let o={},i=["className","id","src","alt","href","type","name","value"],a=new Set([...i,...t.extractAttributes||[]]);for(let s of e.attributes)if(s.type==="JSXAttribute"&&s.name.type==="JSXIdentifier"){let f=s.name.name;if(!a.has(f))continue;if(s.value){let m=k(s.value);m!==void 0&&(o[f]=m)}else o[f]="true"}else s.type==="JSXSpreadAttribute"&&(o["[spread]"]="true");let n="";return r&&r.children&&(n=r.children.map(s=>s.type==="JSXText"?s.value.trim():s.type==="JSXExpressionContainer"&&s.expression.type==="StringLiteral"?s.expression.value:"").filter(Boolean).join(" ").trim()),n&&(o.textContent=n),o}function I(e){let t=e.name;return t.type==="JSXIdentifier"?t.name:t.type==="JSXMemberExpression"?U(t):"Unknown"}function U(e){return`${e.object.name}.${e.property.name}`}function g(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function O(e,t,r){return`${e}:${t}:${r}`}function c(e,t){if(!t.verbose)return;let r=e;e.includes("Error")||e.includes("error")?r=u.red(e):e.includes("Tagged")||e.includes("Summary")?r=u.green(e):e.includes("Processing")||e.includes("started")?r=u.blue(e):r=u.yellow(e),console.log(`[component-tagger] ${r}`)}function v(e){return u.green(`Component Tagger Summary:
- Total files scanned: ${u.cyan(e.totalFiles)}
- Files processed: ${u.cyan(e.processedFiles)}
- Elements tagged: ${u.cyan(e.totalElements)}`)}async function X(e,t,r){if(!x(t,r)||t.includes("node_modules")&&!r.processNodeModules||r.excludeDirectories&&r.excludeDirectories.some(n=>t.includes(n)))return null;let o=process.cwd(),i=b.relative(o,t),a=b.basename(t);c(`Processing file: ${i}`,r);try{let s=V(e,{sourceType:"module",plugins:["jsx","typescript"]}),f=A(s),m=new W(e),S=0,h=null;return q(s,{JSXElement:E=>{h=E.node},JSXOpeningElement:E=>{if(!h)return;let d=E.node,T=I(d);if(!B(T,r,f))return;let R=_(d,r,h),G={elementName:T};Object.entries(R).forEach(([C,p])=>{G[C]=p});let y=d.loc?.start?.line??0,P=d.loc?.start?.column??0,w=h?.loc?.end?.line??y,D=r.generateComponentId?r.generateComponentId(i,y,P):O(i,y,P),l=` ${r.attributePrefix}-id="${g(D)}"`;if(r.includeLegacyAttributes&&(l+=` ${r.attributePrefix}-path="${g(i)}"`,l+=` ${r.attributePrefix}-line="${y}"`,l+=` ${r.attributePrefix}-end-line="${w}"`,l+=` ${r.attributePrefix}-file="${g(a)}"`,l+=` ${r.attributePrefix}-name="${g(T)}"`),r.includeContentAttribute){let C=JSON.stringify(G),p=encodeURIComponent(C);r.maxContentLength&&p.length>r.maxContentLength&&(p=p.substring(0,r.maxContentLength)+"..."),l+=` ${r.attributePrefix}-content="${p}"`}m.appendLeft(d.name.end??0,l),c(l.toString(),r),S++}}),S>0?(c(`Tagged ${S} components in ${i}`,r),{code:m.toString(),map:r.sourceMaps?m.generateMap({hires:!0}):null}):null}catch(n){return console.error(`Error processing file ${i}:`,n),null}}var F=K((e={})=>{let t={extensions:[".jsx",".tsx",".js",".ts"],verbose:!1,attributePrefix:"data-component",includeContentAttribute:!0,maxContentLength:1e3,includeLegacyAttributes:!0,sourceMaps:!0,excludeDirectories:[],processNodeModules:!1,...e},r={totalFiles:0,processedFiles:0,totalElements:0};return{name:"component-tagger",transformInclude(o){return x(o,t)},async transform(o,i){if(i.includes("node_modules")&&!t.processNodeModules||t.excludeDirectories&&t.excludeDirectories.some(n=>i.includes(n)))return null;r.totalFiles++;let a=await X(o,i,t);if(a){r.processedFiles++;let n=(a.code.match(new RegExp(`${t.attributePrefix}-id="`,"g"))||[]).length;r.totalElements+=n}else r.processedFiles++;return a},buildStart(){c("Component tagger plugin started",t),r.totalFiles=0,r.processedFiles=0,r.totalElements=0},buildEnd(){c(v(r),t)}}});function z(e={}){let t=F.vite(e);return{...Array.isArray(t)?t[0]:t,enforce:"pre"}}var pe=z;export{z as createVitePlugin,pe as default};