UNPKG

@stencil/react-output-target

Version:

React output target for @stencil/core components.

333 lines (326 loc) • 11.5 kB
import N, { isAbsolute as k, relative as K } from "node:path"; const I = (n) => n.toLowerCase().split("-").map((o) => o.charAt(0).toUpperCase() + o.slice(1)).join(""), W = (n) => n.replace(/-([_a-z])/g, (o, r) => r.toUpperCase()), Q = (n) => n.replace(/\/([a-z])/g, (o, r) => r.toUpperCase()), X = (n) => { const o = Q(n); return W(`on-${o}`); }, Z = (n) => n.replace(/\/\/.*$/gm, "").replace(/\n/g, " ").replace(/\s{2,}/g, " ").trim(), q = ({ 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(` `) + ` `; }, tt = `/** * 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. */`, D = ({ 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 = /* @__PURE__ */ new Set(); for (const t of n) { const p = t.tagName, a = I(p), u = `${a}Element`, _ = `${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 j = []; for (const i of t.events || []) { if (i.internal || !i.complexType) continue; const { references: v = {}, original: Y } = i.complexType; for (const z of Object.keys(v)) v[z].location !== "global" && l.add(z); j.push({ originalName: i.name, name: X(i.name), type: `EventName<${_}<${Z(Y)}>>` }); } j.length && l.add(_); const b = `${a}Events`, A = t.properties.filter((i) => i.required && !i.internal).map((i) => `'${i.name}'`), S = A.length > 0 ? `, ${A.join(" | ")}` : "", V = j.length > 0 ? `{ ${j.map(({ name: i, type: v }) => `${i}: ${v}`).join(`, `)} }` : "NonNullable<unknown>"; e.push(`export type ${b} = ${V};`); const F = [ `/*@__PURE__*/ createComponent<${u}, ${b}, Components.${a}${S}>({`, ` tagName: '${p}',`, ` elementClass: ${u},`, " // @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project.", " react: React,", ` events: ${j.length ? `{ ${j.map((i) => `${i.name}: '${i.originalName}'`).join(`, `)} }` : "{}"} as ${b},`, ` defineCustomElement: define${a},`, g && " transformTag,", "})" ].filter(Boolean).join(` `), P = t.properties.filter(({ attribute: i }) => !!i).map(({ name: i, attribute: v }) => `${i}: '${v}'`).join(`, `), x = [ `/*@__PURE__*/ createComponent<${u}, ${b}, Components.${a}${S}>({`, ` tagName: '${p}',`, ` properties: {${P ? ` ${P} ` : ""}},`, ` hydrateModule: typeof window === 'undefined' ? (import('${c}') as Promise<HydrateModule>) : undefined,`, ` clientModule: clientComponents.${a} as StencilReactComponent<${u}, ${b}, Components.${a}${S}>,`, " serializeShadowRoot,", g && " getTagTransformer,", "})" ].filter(Boolean).join(` `), H = `StencilReactComponent<${u}, ${b}, Components.${a}${S}>`; e.push( `export const ${a}: ${H} = ${c ? x : 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';` ), [ /** * both files get the `use client` directive; the server file switches to the * server component at runtime (see runtime/ssr.tsx). */ `'use client'; `, tt + ` `, `/* eslint-disable */ `, h.filter(Boolean).join(` `) + ` `, e.filter(Boolean).join(` `) + ` ` ].join(` `); }, et = ({ 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; `, ot = ({ 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 = N.join(r, `${p}.ts`); if (e[a] = D({ components: t, stencilPackageName: n, customElementsDir: c, componentsTypesDir: $, exportMaps: E, typesFromComponentsFile: h, transformTag: T }), T && (e[N.join(r, "tag-transformer.ts")] = et({ stencilPackageName: n, customElementsDir: c, exportMaps: E })), g) { const u = N.join(r, `${p}.server.ts`); e[u] = D({ components: t.filter((_) => !(d != null && d.includes(_.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[N.join(r, "components.ts")] = q({ components: l }), g && (e[N.join(r, "components.server.ts")] = q({ components: l.filter( (t) => !d || !d.includes(t.tagName) ), componentSuffix: ".server", serializeShadowRoot: f })); } else s(l); return e; }, C = "react-output-target", M = "dist/components", O = "dist-custom-elements", R = "standalone", L = "dist-hydrate-script", B = "ssr", nt = "types", st = "dist/types", U = (n, o) => (k(o) ? K(n, o) : o).replace(/\\/g, "/"), at = ({ outDir: n, esModules: o, stencilPackageName: r, excludeComponents: w, customElementsDir: c, hydrateModule: $, clientModule: m, excludeServerSideRenderingFor: g, serializeShadowRoot: y, transformTag: d }) => { let f = M, T = M, 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 === nt), p = (t == null ? void 0 : t.dir) ?? st; 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 = ot({ 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, _]) => l.fs.writeFile(u, _)) ), t.finish(`generate ${C} finished`); }, __internal_getCustomElementsDir() { return f; } }; }; export { at as reactOutputTarget }; //# sourceMappingURL=index.js.map