UNPKG

@stencil/react-output-target

Version:

React output target for @stencil/core components.

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