@stencil/react-output-target
Version:
React output target for @stencil/core components.
42 lines (38 loc) • 6.65 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("ts-morph"),N=require("node:path"),R=o=>o.toLowerCase().split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(""),F=o=>o.replace(/-([_a-z])/g,(r,s)=>s.toUpperCase()),I=o=>o.replace(/\/([a-z])/g,(r,s)=>s.toUpperCase()),j=o=>{const r=I(o);return F(`on-${r}`)},P=async({components:o,project:r,outDir:s})=>{const u=r||new E.Project({useInMemoryFileSystem:!0}),d=`/* eslint-disable */
`,f=`/**
* This file was automatically generated by the Stencil React Output Target.
* Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
*/
`,$=N.join(s||"","components.ts"),l=u.createSourceFile($,f+d,{overwrite:!0});for(const m of o){const i=m.tagName,e=R(i),a=m.tagName;l.addExportDeclaration({moduleSpecifier:`./${a}.js`,namedExports:[e]})}return l.organizeImports(),l.formatText(),await l.save(),l},O=({components:o,stencilPackageName:r,customElementsDir:s,hydrateModule:u,serializeShadowRoot:d})=>{const f=new E.Project({useInMemoryFileSystem:!0}),$=u?"":`'use client';
`,l=`/**
* This file was automatically generated by the Stencil React Output Target.
* Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
*/
`,m=`/* eslint-disable */
`,i=u?"import { createComponent, type SerializeShadowRootOptions, type HydrateModule } from '@stencil/react-output-target/ssr';":"import { createComponent } from '@stencil/react-output-target/runtime';",e=f.createSourceFile("component.ts",`${$}${l}${m}
import React from 'react';
${i}
import type { EventName, StencilReactComponent } from '@stencil/react-output-target/runtime';
`);u&&e.addVariableStatement({isExported:!0,declarationKind:E.VariableDeclarationKind.Const,declarations:[{name:"serializeShadowRoot",type:"SerializeShadowRootOptions",initializer:d?JSON.stringify(d):'{ default: "declarative-shadow-dom" }'}]});for(const a of o){const g=a.tagName,c=R(g),n=`${c}Element`,p=`${c}CustomEvent`;e.addImportDeclaration({moduleSpecifier:`${r}/${s}/${g}.js`,namedImports:[{name:c,alias:n},{name:"defineCustomElement",alias:`define${c}`}]});const h=(a.events||[]).filter(t=>t.internal===!1),y=[];for(const t of h)if(Object.keys(t.complexType.references).length>0){for(const _ of Object.keys(t.complexType.references))t.complexType.references[_].location==="global"||e.addImportDeclaration({moduleSpecifier:r,namedImports:[{name:_,isTypeOnly:!0}]});e.addImportDeclaration({moduleSpecifier:r,namedImports:[{name:p,isTypeOnly:!0}]}),y.push({originalName:t.name,name:j(t.name),type:`EventName<${p}<${t.complexType.original}>>`})}else y.push({originalName:t.name,name:j(t.name),type:`EventName<CustomEvent<${t.complexType.original}>>`});const T=`${c}Events`;e.addTypeAlias({isExported:!0,name:T,type:y.length>0?`{ ${y.map(t=>`${t.name}: ${t.type}`).join(`,
`)} }`:"NonNullable<unknown>"});const S=`/*@__PURE__*/ createComponent<${n}, ${T}>({
tagName: '${g}',
elementClass: ${n},
// @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project.
react: React,
events: {${y.map(t=>`${t.name}: '${t.originalName}'`).join(`,
`)}} as ${T},
defineCustomElement: define${c}
})`,b=`/*@__PURE__*/ createComponent<${n}, ${T}>({
tagName: '${g}',
properties: {${a.properties.filter(t=>!!t.attribute).map(t=>`${t.name}: '${t.attribute}'`).join(`,
`)}},
hydrateModule: import('${u}') as Promise<HydrateModule>,
serializeShadowRoot,
elementClass: ${n},
// @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project.
react: React,
events: {${y.map(t=>`${t.name}: '${t.originalName}'`).join(`,
`)}} as ${T},
defineCustomElement: define${c}
})`;e.addVariableStatement({isExported:!0,declarationKind:E.VariableDeclarationKind.Const,declarations:[{name:c,type:`StencilReactComponent<${n}, ${T}>`,initializer:u?b:S}]})}return e.organizeImports(),e.formatText(),e.getFullText()},U=async({stencilPackageName:o,components:r,outDir:s,esModules:u,customElementsDir:d,excludeComponents:f,project:$,hydrateModule:l,excludeServerSideRenderingFor:m,serializeShadowRoot:i})=>{const e=[],a=r.filter(n=>!(n.internal===!0||f!=null&&f.includes(n.tagName)));if(a.length===0)return[];const g={};function c(n,p="components"){const h=N.join(s,`${p}.ts`),y=O({components:n,stencilPackageName:o,customElementsDir:d});if(g[h]=y,l){const T=N.join(s,`${p}.server.ts`),S=O({components:n.filter(b=>!m||!m.includes(b.tagName)),stencilPackageName:o,customElementsDir:d,hydrateModule:l,serializeShadowRoot:i});g[T]=S}}if(u){for(const p of a)c([p],p.tagName);const n=await P({components:a,project:$,outDir:s});e.push(n)}else c(a);return await Promise.all(Object.entries(g).map(async([n,p])=>{const h=$.createSourceFile(n,p,{overwrite:!0});await h.save(),e.push(h)})),e},C="react-output-target",D="dist/components",w="dist-custom-elements",v="dist-hydrate-script",x=({outDir:o,esModules:r,stencilPackageName:s,excludeComponents:u,customElementsDir:d,hydrateModule:f,excludeServerSideRenderingFor:$,serializeShadowRoot:l})=>{let m=D;return{type:"custom",name:C,validate(i){if(d)m=d;else{const e=(i.outputTargets||[]).find(a=>a.type===w);if(e==null)throw new Error(`The '${C}' requires '${w}' output target. Add { type: '${w}' }, to the outputTargets config.`);if(e.dir!==void 0&&(m=e.dir),e.externalRuntime!==!1)throw new Error(`The '${C}' requires the '${w}' output target to have 'externalRuntime: false' set in its configuration.`)}if(f&&(i.outputTargets||[]).find(a=>a.type===v)==null)throw new Error(`The '${C}' requires '${v}' output target when the 'hydrateModule' option is set. Add { type: '${v}' }, to the outputTargets config.`);if(!o)throw new Error("The 'outDir' option is required.");if(s===void 0){if(i.sys&&i.packageJsonFilePath){const{name:e}=JSON.parse(i.sys.readFileSync(i.packageJsonFilePath,"utf8"));s=e}if(!s)throw new Error(`Unable to find the package name in the package.json file: ${i.packageJsonFilePath}. Please provide the stencilPackageName manually to the ${C} output target.`)}},async generator(i,e,a){const g=a.createTimeSpan(`generate ${C} started`,!0),c=a.components,n=new E.Project,p=await U({outDir:o,components:c,stencilPackageName:s,customElementsDir:m,excludeComponents:u,esModules:r===!0,project:n,hydrateModule:f,excludeServerSideRenderingFor:$,serializeShadowRoot:l});await Promise.all(p.map(h=>e.fs.writeFile(h.getFilePath(),h.getFullText()))),g.finish(`generate ${C} finished`)},__internal_getCustomElementsDir(){return m}}};exports.reactOutputTarget=x;
//# sourceMappingURL=index.cjs.map