UNPKG

@stencil/react-output-target

Version:

React output target for @stencil/core components.

61 lines (53 loc) • 10.1 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("node:path"),j=require("ts-morph"),J=t=>t.toLowerCase().split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(""),W=t=>t.replace(/-([_a-z])/g,(n,l)=>l.toUpperCase()),Q=t=>t.replace(/\/([a-z])/g,(n,l)=>l.toUpperCase()),X=t=>{const n=Q(t);return W(`on-${n}`)},Z=t=>t.replace(/\/\/.*$/gm,"").replace(/\n/g," ").replace(/\s{2,}/g," ").trim(),V=async({components:t,project:n,outDir:l,filename:b="components.ts",componentSuffix:p="",serializeShadowRoot:g})=>{const $=n||new j.Project({useInMemoryFileSystem:!0}),T=`/* eslint-disable */ `,y=`/** * 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. */ `,v=I.join(l||"",b),c=$.createSourceFile(v,y+T,{overwrite:!0});p&&(c.addImportDeclaration({moduleSpecifier:"@stencil/react-output-target/ssr",namedImports:[{name:"SerializeShadowRootOptions",isTypeOnly:!0}]}),c.addVariableStatement({isExported:!0,declarationKind:j.VariableDeclarationKind.Const,declarations:[{name:"serializeShadowRoot",type:"SerializeShadowRootOptions",initializer:g?JSON.stringify(g):'{ default: "declarative-shadow-dom" }'}]}));for(const f of t){const h=f.tagName,S=J(h),r=f.tagName;c.addExportDeclaration({moduleSpecifier:`./${r}${p}.js`,namedExports:[S]})}return c.organizeImports(),c.formatText(),await c.save(),c},M=({components:t,stencilPackageName:n,customElementsDir:l,componentsTypesDir:b,hydrateModule:p,clientModule:g,serializeShadowRoot:$,transformTag:T,exportMaps:y,typesFromComponentsFile:v})=>{const c=new j.Project({useInMemoryFileSystem:!0}),f=y?`${n}/components`:`${n}/${b}`,h=y||v?f:n,S=`'use client'; `,r=`/** * 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. */ `,C=`/* eslint-disable */ `,i=p?[T?`import { getTagTransformer } from './tag-transformer.js'; `:"","import { createComponent, type SerializeShadowRootOptions, type HydrateModule, type ReactWebComponent } from '@stencil/react-output-target/ssr';"].filter(Boolean).join(` `):"import { createComponent } from '@stencil/react-output-target/runtime';",d=T?`import { transformTag } from './tag-transformer.js'; `:"",e=c.createSourceFile("component.ts",`${S}${r}${C} import React from 'react'; ${i} import type { EventName, StencilReactComponent } from '@stencil/react-output-target/runtime'; ${d} import type { Components } from "${f}"; `);p&&g&&e.addImportDeclaration({moduleSpecifier:g,namespaceImport:"clientComponents"}),p&&e.addVariableStatement({isExported:!0,declarationKind:j.VariableDeclarationKind.Const,declarations:[{name:"serializeShadowRoot",type:"SerializeShadowRootOptions",initializer:$?JSON.stringify($):'{ default: "declarative-shadow-dom" }'}]});for(const s of t){const m=s.tagName,u=J(m),E=`${u}Element`,N=`${u}CustomEvent`;e.addImportDeclaration({moduleSpecifier:y?`${n}/${m}`:`${n}/${l}/${m}.js`,namedImports:[{name:u,alias:E},{name:"defineCustomElement",alias:`define${u}`}]});const F=(s.events||[]).filter(o=>o.internal===!1),O=[],x=new Set;let z=!1;for(const o of F){if(Object.keys(o.complexType.references).length>0)for(const D of Object.keys(o.complexType.references))!(o.complexType.references[D].location==="global")&&!x.has(D)&&(x.add(D),e.addImportDeclaration({moduleSpecifier:h,namedImports:[{name:D,isTypeOnly:!0}]}));z||(z=!0,e.addImportDeclaration({moduleSpecifier:h,namedImports:[{name:N,isTypeOnly:!0}]})),O.push({originalName:o.name,name:X(o.name),type:`EventName<${N}<${Z(o.complexType.original)}>>`})}const _=`${u}Events`,q=s.properties.filter(o=>o.required&&!o.internal).map(o=>`'${o.name}'`),R=q.length>0?`, ${q.join(" | ")}`:"";e.addTypeAlias({isExported:!0,name:_,type:O.length>0?`{ ${O.map(o=>`${o.name}: ${o.type}`).join(`, `)} }`:"NonNullable<unknown>"});const H=T?`, transformTag`:"",Y=`/*@__PURE__*/ createComponent<${E}, ${_}, Components.${u}${R}>({ tagName: '${m}', elementClass: ${E}, // @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project. react: React, events: {${O.map(o=>`${o.name}: '${o.originalName}'`).join(`, `)}} as ${_}, defineCustomElement: define${u}${H} })`,k=T?`, getTagTransformer`:"",B=`/*@__PURE__*/ createComponent<${E}, ${_}, Components.${u}${R}>({ tagName: '${m}', properties: {${s.properties.filter(o=>!!o.attribute).map(o=>`${o.name}: '${o.attribute}'`).join(`, `)}}, hydrateModule: typeof window === 'undefined' ? (import('${p}') as Promise<HydrateModule>) : undefined, clientModule: clientComponents.${u} as StencilReactComponent<${E}, ${_}, Components.${u}${R}>, serializeShadowRoot${k} })`;e.addVariableStatement({isExported:!0,declarationKind:j.VariableDeclarationKind.Const,declarations:[{name:u,type:`StencilReactComponent<${E}, ${_}, Components.${u}${R}>`,initializer:p?B:Y}]})}if(e.organizeImports(),p&&g){const s=e.getImportDeclarations().find(m=>{var u;return((u=m.getNamespaceImport())==null?void 0:u.getText())==="clientComponents"});s&&e.insertText(s.getStart(),`// @ts-ignore - ignore potential type issues as the project is importing itself `)}return e.formatText(),e.getFullText()},ee=({stencilPackageName:t,customElementsDir:n,exportMaps:l})=>`/* eslint-disable */ /* tslint:disable */ import { setTagTransformer as clientSetTagTransformer } from '${l?`${t}/standalone`:`${t}/${n}/index.js`}'; let tagTransformer: ((tagName: string) => string) | undefined; export const setTagTransformer = (transformer: (tagName: string) => string) => { clientSetTagTransformer(transformer); tagTransformer = transformer; }; export const transformTag = (tag: string): string => { return tagTransformer ? tagTransformer(tag) : tag; }; export const getTagTransformer = () => tagTransformer; `,te=async({stencilPackageName:t,components:n,outDir:l,esModules:b,customElementsDir:p,componentsTypesDir:g,excludeComponents:$,project:T,hydrateModule:y,clientModule:v,excludeServerSideRenderingFor:c,serializeShadowRoot:f,transformTag:h,exportMaps:S,typesFromComponentsFile:r})=>{const C=[],a=n.filter(e=>!(e.internal===!0||$!=null&&$.includes(e.tagName)));if(a.length===0)return[];const i={};function d(e,s="components"){const m=I.join(l,`${s}.ts`),u=M({components:e,stencilPackageName:t,customElementsDir:p,componentsTypesDir:g,exportMaps:S,typesFromComponentsFile:r,transformTag:h});if(i[m]=u,h){const E=I.join(l,"tag-transformer.ts");i[E]=ee({stencilPackageName:t,customElementsDir:p,exportMaps:S})}if(y){const E=I.join(l,`${s}.server.ts`),N=M({components:e.filter(F=>!c||!c.includes(F.tagName)),stencilPackageName:t,customElementsDir:p,componentsTypesDir:g,exportMaps:S,typesFromComponentsFile:r,hydrateModule:y,clientModule:v,serializeShadowRoot:f,transformTag:h});i[E]=N}}if(b){for(const s of a)d([s],s.tagName);const e=await V({components:a,project:T,outDir:l});if(C.push(e),y){const s=await V({components:a.filter(m=>!c||!c.includes(m.tagName)),project:T,outDir:l,filename:"components.server.ts",componentSuffix:".server",serializeShadowRoot:f});C.push(s)}}else d(a);return await Promise.all(Object.entries(i).map(async([e,s])=>{const m=T.createSourceFile(e,s,{overwrite:!0});await m.save(),C.push(m)})),C},w="react-output-target",L="dist/components",P="dist-custom-elements",U="standalone",G="dist-hydrate-script",K="ssr",ne="types",oe="dist/types",A=(t,n)=>(I.isAbsolute(n)?I.relative(t,n):n).replace(/\\/g,"/"),re=({outDir:t,esModules:n,stencilPackageName:l,excludeComponents:b,customElementsDir:p,hydrateModule:g,clientModule:$,excludeServerSideRenderingFor:T,serializeShadowRoot:y,transformTag:v})=>{let c=L,f=L,h=!1,S=!1;return{type:"custom",name:w,validate(r){const C=(r.outputTargets||[]).some(a=>["loader-bundle","standalone","ssr","types"].includes(a.type));if(h=C&&r.generateExportMaps===!0,S=C,p)c=p,f=p;else{const a=(r.outputTargets||[]).find(i=>i.type===P||i.type===U);if(a==null){const d=(r.outputTargets||[]).some(e=>["loader-bundle","standalone","ssr","types"].includes(e.type))?U:P;throw new Error(`The '${w}' requires '${d}' output target. Add { type: '${d}' }, to the outputTargets config.`)}if(a.type===U){const i=(r.outputTargets||[]).find(s=>s.type===ne),d=(i==null?void 0:i.dir)??oe;if(f=`${A(r.rootDir,d)}/components`,a.dir!==void 0){const s=a.dir;c=A(r.rootDir,s)}}else if(a.dir!==void 0){const i=a.dir;c=A(r.rootDir,i),f=c}if(a.type===P&&a.externalRuntime!==!1)throw new Error(`The '${w}' requires the '${P}' output target to have 'externalRuntime: false' set in its configuration.`)}if(g){if((r.outputTargets||[]).find(i=>i.type===G||i.type===K)==null){const d=(r.outputTargets||[]).some(e=>["loader-bundle","standalone","ssr","types"].includes(e.type))?K:G;throw new Error(`The '${w}' requires '${d}' output target when the 'hydrateModule' option is set. Add { type: '${d}' }, to the outputTargets config.`)}if($==null)throw new Error(`The '${w}' requires the 'clientModule' option when the 'hydrateModule' option is set. Please provide the clientModule manually to the ${w} output target.`)}if(l===void 0){if(r.sys&&r.packageJsonFilePath){const{name:a}=JSON.parse(r.sys.readFileSync(r.packageJsonFilePath,"utf8"));l=a}if(!l)throw new Error(`Unable to find the package name in the package.json file: ${r.packageJsonFilePath}. Please provide the stencilPackageName manually to the ${w} output target.`)}},async generator(r,C,a){const i=a.createTimeSpan(`generate ${w} started`,!0),d=a.components,e=new j.Project,s=await te({outDir:t,components:d,stencilPackageName:l,customElementsDir:c,componentsTypesDir:f,excludeComponents:b,esModules:n===!0,project:e,hydrateModule:g,clientModule:$,excludeServerSideRenderingFor:T,serializeShadowRoot:y,transformTag:v,exportMaps:h,typesFromComponentsFile:S});await Promise.all(s.map(m=>C.fs.writeFile(m.getFilePath(),m.getFullText()))),i.finish(`generate ${w} finished`)},__internal_getCustomElementsDir(){return c}}};exports.reactOutputTarget=re; //# sourceMappingURL=index.cjs.map