UNPKG

@stencil/react-output-target

Version:

React output target for @stencil/core components.

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