UNPKG

@dhiwise/component-tagger

Version:

Automatically annotate JSX components and HTML elements with data attributes

2 lines (1 loc) 7.53 kB
import*as b from"path";import{parse as j}from"@babel/parser";import{traverse as q}from"@babel/core";import U from"magic-string";import D from"picomatch";var L=new Set(["Fragment","Suspense","StrictMode","Profiler","React.Fragment"]),P=["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"],J=["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 h={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 $(e){let t=new Set;for(let r of e.program.body)if(r.type==="ImportDeclaration"){let n=r,a=n.source.value;if(P.some(o=>a===o||a.startsWith(o+"/")))for(let o of n.specifiers)o.type==="ImportSpecifier"||o.type==="ImportDefaultSpecifier"?t.add(o.local.name):o.type==="ImportNamespaceSpecifier"&&t.add(`${o.local.name}.*`)}return t}var C=new Map;function F(e){let t=e.sort().join(",");if(!C.has(t)){let r=e.map(a=>`**/*${a}`),n=D(r);C.set(t,n)}return C.get(t)}function B(e,t){let r=t.extensions||[".jsx",".tsx",".js",".ts"];return F(r)(e)?![".test.",".spec.","__tests__","__mocks__"].some(o=>e.includes(o)):!1}function A(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&&H(e,r))}function H(e,t){if(t.has(e)||J.includes(e))return!0;for(let r of t)if(r.endsWith(".*")){let n=r.slice(0,-2);if(e.startsWith(`${n}.`))return!0}return!1}function N(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:"",n=t.right.type==="StringLiteral"?t.right.value:"";return r+n}if(t.type==="Identifier")return`[var:${t.name}]`}}}function _(e,t,r){let n={},a=["className","id","src","alt","href","type","name","value"],c=new Set([...a,...t.extractAttributes||[]]);for(let i of e.attributes)if(i.type==="JSXAttribute"&&i.name.type==="JSXIdentifier"){let m=i.name.name;if(!c.has(m))continue;if(i.value){let l=N(i.value);l!==void 0&&(n[m]=l)}else n[m]="true"}else i.type==="JSXSpreadAttribute"&&(n["[spread]"]="true");let o="";return r&&r.children&&(o=r.children.map(i=>i.type==="JSXText"?i.value.trim():i.type==="JSXExpressionContainer"&&i.expression.type==="StringLiteral"?i.expression.value:"").filter(Boolean).join(" ").trim()),o&&(n.textContent=o),n}function I(e){let t=e.name;return t.type==="JSXIdentifier"?t.name:t.type==="JSXMemberExpression"?k(t):"Unknown"}function k(e){return`${e.object.name}.${e.property.name}`}function p(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function O(e,t,r){return`${e}:${t}:${r}`}function y(e,t){if(!t.verbose)return;let r=e;e.includes("Error")||e.includes("error")?r=h.red(e):e.includes("Tagged")||e.includes("Summary")?r=h.green(e):e.includes("Processing")||e.includes("started")?r=h.blue(e):r=h.yellow(e),console.log(`[component-tagger] ${r}`)}async function X(e,t,r){if(!B(t,r)||t.includes("node_modules")&&!r.processNodeModules||r.excludeDirectories&&r.excludeDirectories.some(o=>t.includes(o)))return null;let n=process.cwd(),a=b.relative(n,t),c=b.basename(t);y(`Processing file: ${a}`,r);try{let i=j(e,{sourceType:"module",plugins:["jsx","typescript"]}),m=$(i),l=new U(e),x=0,d=null;return q(i,{JSXElement:S=>{d=S.node},JSXOpeningElement:S=>{if(!d)return;let f=S.node,E=I(f);if(!A(E,r,m))return;let v=_(f,r,d),M={elementName:E};Object.entries(v).forEach(([T,u])=>{M[T]=u});let g=f.loc?.start?.line??0,G=f.loc?.start?.column??0,w=d?.loc?.end?.line??g,R=r.generateComponentId?r.generateComponentId(a,g,G):O(a,g,G),s=` ${r.attributePrefix}-id="${p(R)}"`;if(r.includeLegacyAttributes&&(s+=` ${r.attributePrefix}-path="${p(a)}"`,s+=` ${r.attributePrefix}-line="${g}"`,s+=` ${r.attributePrefix}-end-line="${w}"`,s+=` ${r.attributePrefix}-file="${p(c)}"`,s+=` ${r.attributePrefix}-name="${p(E)}"`),r.includeContentAttribute){let T=JSON.stringify(M),u=encodeURIComponent(T);r.maxContentLength&&u.length>r.maxContentLength&&(u=u.substring(0,r.maxContentLength)+"..."),s+=` ${r.attributePrefix}-content="${u}"`}l.appendLeft(f.name.end??0,s),y(s.toString(),r),x++}}),x>0?(y(`Tagged ${x} components in ${a}`,r),{code:l.toString(),map:r.sourceMaps?l.generateMap({hires:!0}):null}):null}catch(o){return console.error(`Error processing file ${a}:`,o),null}}async function V(e){let t=this.resourcePath,r={extensions:[".jsx",".tsx",".js",".ts"],verbose:!1,attributePrefix:"data-component",includeContentAttribute:!0,maxContentLength:1e3,includeLegacyAttributes:!0,sourceMaps:!0,excludeDirectories:[],processNodeModules:!1,...this.query};try{let n=await X(e,t,r);return n?n.code:e}catch{return e}}var ie=V;export{ie as default};