@stencil/react-output-target
Version:
React output target for @stencil/core components.
1 lines • 37.9 kB
Source Map (JSON)
{"version":3,"file":"ssr.cjs","sources":["../../../node_modules/.pnpm/@emotion+unitless@0.10.0/node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../../../node_modules/.pnpm/react-style-stringify@1.2.0/node_modules/react-style-stringify/dist/index.mjs","../src/runtime/constants.ts","../src/runtime/ssr.tsx"],"sourcesContent":["var unitlessKeys = {\n animationIterationCount: 1,\n aspectRatio: 1,\n borderImageOutset: 1,\n borderImageSlice: 1,\n borderImageWidth: 1,\n boxFlex: 1,\n boxFlexGroup: 1,\n boxOrdinalGroup: 1,\n columnCount: 1,\n columns: 1,\n flex: 1,\n flexGrow: 1,\n flexPositive: 1,\n flexShrink: 1,\n flexNegative: 1,\n flexOrder: 1,\n gridRow: 1,\n gridRowEnd: 1,\n gridRowSpan: 1,\n gridRowStart: 1,\n gridColumn: 1,\n gridColumnEnd: 1,\n gridColumnSpan: 1,\n gridColumnStart: 1,\n msGridRow: 1,\n msGridRowSpan: 1,\n msGridColumn: 1,\n msGridColumnSpan: 1,\n fontWeight: 1,\n lineHeight: 1,\n opacity: 1,\n order: 1,\n orphans: 1,\n scale: 1,\n tabSize: 1,\n widows: 1,\n zIndex: 1,\n zoom: 1,\n WebkitLineClamp: 1,\n // SVG-related properties\n fillOpacity: 1,\n floodOpacity: 1,\n stopOpacity: 1,\n strokeDasharray: 1,\n strokeDashoffset: 1,\n strokeMiterlimit: 1,\n strokeOpacity: 1,\n strokeWidth: 1\n};\n\nexport { unitlessKeys as default };\n","// src/helpers.ts\nimport unitless from \"@emotion/unitless\";\nvar DEFAULT_UNIT = \"px\";\nvar isCSSPropertyValue = (value) => typeof value === \"number\" || typeof value === \"string\";\nfunction camelToKebab(str) {\n return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);\n}\nfunction trimCssSelector(selector) {\n return selector.replace(/\\s*([+~>])\\s*/g, \"$1\").replace(/\\s{2,}/g, \" \").trim();\n}\nfunction applyCssUnits(property, value, unit = DEFAULT_UNIT) {\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n throw new Error(\n \"Invalid input: value of 'cssProperties' must be string or number.\"\n );\n }\n const isUnitless = unitless[property] === 1;\n if (typeof value === \"string\" || value === 0 || isUnitless) {\n return `${value}`;\n }\n const resolvedUnit = (typeof unit === \"string\" ? unit : unit[property]) || DEFAULT_UNIT;\n return `${value}${resolvedUnit}`;\n}\n\n// src/stringifyStyleDeclaration.ts\nfunction stringifyStyleDeclaration(styleDeclaration, options) {\n if (typeof styleDeclaration !== \"object\" || styleDeclaration === null) {\n throw new TypeError(\n `[stringifyStyleDeclaration]: Expected 'styleDeclaration' to be a non-null object, but received ${styleDeclaration} (type:${typeof styleDeclaration}).`\n );\n }\n const importantSuffix = options?.important ? \"!important\" : \"\";\n return Object.entries(styleDeclaration).filter(([_, value]) => isCSSPropertyValue(value)).map(\n ([property, value]) => `${camelToKebab(property)}:${applyCssUnits(\n property,\n value,\n options?.unit\n )}${importantSuffix};`\n ).join(\"\");\n}\n\n// src/stringifyStyleRule.ts\nfunction stringifyStyleRule(styleRule, options) {\n if (typeof styleRule !== \"object\" || styleRule === null) {\n throw new TypeError(\n `[stringifyStyleRule]: Expected 'styleRule' to be a non-null object, but received ${styleRule} (type:${typeof styleRule}).`\n );\n }\n return Object.entries(styleRule).reduce((result, [selector, declaration]) => {\n if (Object.keys(declaration).length > 0) {\n result.push(\n `${trimCssSelector(selector)}{${stringifyStyleDeclaration(\n declaration,\n options\n )}}`\n );\n }\n return result;\n }, []).join(\"\");\n}\n\n// src/stringify-react-styles.ts\nfunction stringifyCSSProperties(cssProperties, optionsOrImportant = false) {\n if (typeof cssProperties !== \"object\" || cssProperties === null) {\n throw new TypeError(\n `[stringifyCSSProperties]: Expected 'cssProperties' to be a non-null object, but received ${cssProperties} (type:${typeof cssProperties}).`\n );\n }\n const options = typeof optionsOrImportant === \"boolean\" ? {\n important: optionsOrImportant\n } : optionsOrImportant;\n return stringifyStyleDeclaration(cssProperties, options);\n}\nfunction stringifyStyleMap(styleMap, optionsOrImportant = false) {\n if (typeof styleMap !== \"object\" || styleMap === null) {\n throw new TypeError(\n `[stringifyStyleMap]: Expected 'styleMap' to be a non-null object, but received ${styleMap} (type:${typeof styleMap}).`\n );\n }\n const options = typeof optionsOrImportant === \"boolean\" ? {\n important: optionsOrImportant\n } : optionsOrImportant;\n return stringifyStyleRule(styleMap, options);\n}\nexport {\n stringifyCSSProperties,\n stringifyStyleDeclaration,\n stringifyStyleMap,\n stringifyStyleRule\n};\n//# sourceMappingURL=index.mjs.map","/**\n * Copied from https://github.com/facebook/react/blob/7771d3a7972cc2483c45fde51b7ec2d926cba097/packages/react-dom-bindings/src/shared/possibleStandardNames.js\n * and amended accordingly to remove duplicates and entries where key value pairs are the same.\n */\nexport const possibleStandardNames = {\n acceptCharset: 'accept-charset',\n accessKey: 'accesskey',\n allowFullScreen: 'allowfullscreen',\n autoCapitalize: 'autocapitalize',\n autoComplete: 'autocomplete',\n autoCorrect: 'autocorrect',\n autoFocus: 'autofocus',\n autoPlay: 'autoplay',\n autoSave: 'autosave',\n cellPadding: 'cellpadding',\n cellSpacing: 'cellspacing',\n charSet: 'charset',\n className: 'class',\n classID: 'classid',\n colSpan: 'colspan',\n contentEditable: 'contenteditable',\n contextMenu: 'contextmenu',\n controlsList: 'controlslist',\n crossOrigin: 'crossorigin',\n dangerouslySetInnerHTML: 'dangerouslysetinnerhtml',\n dateTime: 'datetime',\n defaultChecked: 'defaultchecked',\n defaultValue: 'defaultvalue',\n disablePictureInPicture: 'disablepictureinpicture',\n disableRemotePlayback: 'disableremoteplayback',\n encType: 'enctype',\n enterKeyHint: 'enterkeyhint',\n fetchPriority: 'fetchpriority',\n htmlFor: 'for',\n formMethod: 'formmethod',\n formAction: 'formaction',\n formEncType: 'formenctype',\n formNoValidate: 'formnovalidate',\n formTarget: 'formtarget',\n frameBorder: 'frameborder',\n hrefLang: 'hreflang',\n httpEquiv: 'http-equiv',\n imageSizes: 'imagesizes',\n imageSrcSet: 'imagesrcset',\n inputMode: 'inputmode',\n itemID: 'itemid',\n itemProp: 'itemprop',\n itemRef: 'itemref',\n itemScope: 'itemscope',\n itemType: 'itemtype',\n keyParams: 'keyparams',\n keyType: 'keytype',\n marginWidth: 'marginwidth',\n marginHeight: 'marginheight',\n maxLength: 'maxlength',\n mediaGroup: 'mediagroup',\n noModule: 'nomodule',\n noValidate: 'novalidate',\n playsInline: 'playsinline',\n radioGroup: 'radiogroup',\n readOnly: 'readonly',\n referrerPolicy: 'referrerpolicy',\n rowSpan: 'rowspan',\n spellCheck: 'spellcheck',\n srcDoc: 'srcdoc',\n srcLang: 'srclang',\n srcSet: 'srcset',\n tabIndex: 'tabindex',\n useMap: 'usemap',\n accentHeight: 'accent-height',\n alignmentBaseline: 'alignment-baseline',\n arabicForm: 'arabic-form',\n attributeName: 'attributename',\n attributeType: 'attributetype',\n autoReverse: 'autoreverse',\n baseFrequency: 'basefrequency',\n baselineShift: 'baseline-shift',\n baseProfile: 'baseprofile',\n calcMode: 'calcmode',\n capHeight: 'cap-height',\n clipPath: 'clip-path',\n clipPathUnits: 'clippathunits',\n clipRule: 'clip-rule',\n colorInterpolation: 'color-interpolation',\n colorInterpolationFilters: 'color-interpolation-filters',\n colorProfile: 'color-profile',\n colorRendering: 'color-rendering',\n contentScriptType: 'contentscripttype',\n contentStyleType: 'contentstyletype',\n diffuseConstant: 'diffuseconstant',\n dominantBaseline: 'dominant-baseline',\n enableBackground: 'enable-background',\n externalResourcesRequired: 'externalresourcesrequired',\n fillOpacity: 'fill-opacity',\n fillRule: 'fill-rule',\n filterRes: 'filterres',\n filterUnits: 'filterunits',\n floodOpacity: 'flood-opacity',\n floodColor: 'flood-color',\n fontFamily: 'font-family',\n fontSize: 'font-size',\n fontSizeAdjust: 'font-size-adjust',\n fontStretch: 'font-stretch',\n fontStyle: 'font-style',\n fontVariant: 'font-variant',\n fontWeight: 'font-weight',\n glyphName: 'glyph-name',\n glyphOrientationHorizontal: 'glyph-orientation-horizontal',\n glyphOrientationVertical: 'glyph-orientation-vertical',\n gradientTransform: 'gradienttransform',\n gradientUnits: 'gradientunits',\n horizAdvX: 'horiz-adv-x',\n horizOriginX: 'horiz-origin-x',\n imageRendering: 'image-rendering',\n kernelMatrix: 'kernelmatrix',\n kernelUnitLength: 'kernelunitlength',\n keyPoints: 'keypoints',\n keySplines: 'keysplines',\n keyTimes: 'keytimes',\n lengthAdjust: 'lengthadjust',\n letterSpacing: 'letter-spacing',\n lightingColor: 'lighting-color',\n limitingConeAngle: 'limitingconeangle',\n markerEnd: 'marker-end',\n markerHeight: 'markerheight',\n markerMid: 'marker-mid',\n markerStart: 'marker-start',\n markerUnits: 'markerunits',\n markerWidth: 'markerwidth',\n maskContentUnits: 'maskcontentunits',\n maskUnits: 'maskunits',\n numOctaves: 'numoctaves',\n overlinePosition: 'overline-position',\n overlineThickness: 'overline-thickness',\n paintOrder: 'paint-order',\n panose1: 'panose-1',\n pathLength: 'pathlength',\n patternContentUnits: 'patterncontentunits',\n patternTransform: 'patterntransform',\n patternUnits: 'patternunits',\n pointerEvents: 'pointer-events',\n pointsAtX: 'pointsatx',\n pointsAtY: 'pointsaty',\n pointsAtZ: 'pointsatz',\n preserveAlpha: 'preservealpha',\n preserveAspectRatio: 'preserveaspectratio',\n primitiveUnits: 'primitiveunits',\n refX: 'refx',\n refY: 'refy',\n renderingIntent: 'rendering-intent',\n repeatCount: 'repeatcount',\n repeatDur: 'repeatdur',\n requiredExtensions: 'requiredextensions',\n requiredFeatures: 'requiredfeatures',\n shapeRendering: 'shape-rendering',\n slot: 'slot',\n specularConstant: 'specularconstant',\n specularExponent: 'specularexponent',\n spreadMethod: 'spreadmethod',\n startOffset: 'startoffset',\n stdDeviation: 'stddeviation',\n stitchTiles: 'stitchtiles',\n stopColor: 'stop-color',\n stopOpacity: 'stop-opacity',\n strikethroughPosition: 'strikethrough-position',\n strikethroughThickness: 'strikethrough-thickness',\n strokeDasharray: 'stroke-dasharray',\n strokeDashoffset: 'stroke-dashoffset',\n strokeLinecap: 'stroke-linecap',\n strokeLinejoin: 'stroke-linejoin',\n strokeMiterlimit: 'stroke-miterlimit',\n strokeWidth: 'stroke-width',\n strokeOpacity: 'stroke-opacity',\n suppressContentEditableWarning: 'suppresscontenteditablewarning',\n suppressHydrationWarning: 'suppresshydrationwarning',\n surfaceScale: 'surfacescale',\n systemLanguage: 'systemlanguage',\n tableValues: 'tablevalues',\n targetX: 'targetx',\n targetY: 'targety',\n textAnchor: 'text-anchor',\n textDecoration: 'text-decoration',\n textLength: 'textlength',\n textRendering: 'text-rendering',\n transformOrigin: 'transform-origin',\n underlinePosition: 'underline-position',\n underlineThickness: 'underline-thickness',\n unicodeBidi: 'unicode-bidi',\n unicodeRange: 'unicode-range',\n unitsPerEm: 'units-per-em',\n vectorEffect: 'vector-effect',\n vertAdvY: 'vert-adv-y',\n vertOriginX: 'vert-origin-x',\n vertOriginY: 'vert-origin-y',\n wordSpacing: 'word-spacing',\n writingMode: 'writing-mode',\n xChannelSelector: 'xchannelselector',\n xHeight: 'x-height',\n xlinkActuate: 'xlink:actuate',\n xlinkArcrole: 'xlink:arcrole',\n xlinkHref: 'xlink:href',\n xlinkRole: 'xlink:role',\n xlinkShow: 'xlink:show',\n xlinkTitle: 'xlink:title',\n xlinkType: 'xlink:type',\n xmlBase: 'xml:base',\n xmlLang: 'xml:lang',\n xmlnsXlink: 'xmlns:xlink',\n yChannelSelector: 'ychannelselector',\n zoomAndPan: 'zoomandpan',\n};\n","import type { EventName, Options, ReactWebComponent, WebComponentProps } from '@lit/react';\nimport React, { Component, JSXElementConstructor, ReactNode } from 'react';\nimport { stringifyCSSProperties } from 'react-style-stringify';\n\nimport { createComponent as createComponentWrapper } from './create-component.js';\nimport { possibleStandardNames } from './constants.js';\n\nconst LOG_PREFIX = '[react-output-target]';\n\n// A key value map matching React prop names to event names.\ntype EventNames = Record<string, EventName | string>;\n\nexport type SerializeShadowRootOptions =\n | 'declarative-shadow-dom'\n | 'scoped'\n | {\n 'declarative-shadow-dom'?: string[];\n scoped?: string[];\n default: 'declarative-shadow-dom' | 'scoped';\n }\n | boolean;\n\n/**\n * these types are defined by a Stencil hydrate app so we have to copy the minimal types here\n */\nexport interface RenderToStringOptions {\n fullDocument?: boolean;\n prettyHtml?: boolean;\n /**\n * Configure how Stencil serializes the components shadow root.\n * - If set to `declarative-shadow-dom` the component will be rendered within a Declarative Shadow DOM.\n * - If set to `scoped` Stencil will render the contents of the shadow root as a `scoped: true` component\n * and the shadow DOM will be created during client-side hydration.\n * - Alternatively you can mix and match the two by providing an object with `declarative-shadow-dom` and `scoped` keys,\n * the value arrays containing the tag names of the components that should be rendered in that mode.\n *\n * Examples:\n * - `{ 'declarative-shadow-dom': ['my-component-1', 'another-component'], default: 'scoped' }`\n * Render all components as `scoped` apart from `my-component-1` and `another-component`\n * - `{ 'scoped': ['an-option-component'], default: 'declarative-shadow-dom' }`\n * Render all components within `declarative-shadow-dom` apart from `an-option-component`\n * - `'scoped'` Render all components as `scoped`\n * - `false` disables shadow root serialization\n *\n * *NOTE* `true` has been deprecated in favor of `declarative-shadow-dom` and `scoped`\n * @default 'declarative-shadow-dom'\n */\n serializeShadowRoot?: SerializeShadowRootOptions;\n}\ntype RenderToString = (html: string, options: RenderToStringOptions) => Promise<{ html: string | null }>;\n\nexport type HydrateModule = {\n renderToString: RenderToString;\n serializeProperty: (value: any) => string;\n};\ninterface CreateComponentForServerSideRenderingOptions {\n tagName: string;\n properties: Record<string, string>;\n renderToString: RenderToString;\n serializeProperty: (value: any) => string;\n serializeShadowRoot?: SerializeShadowRootOptions;\n}\n\ntype StencilProps<I extends HTMLElement> = WebComponentProps<I>;\n\n// Definition comes from React but is not exported or part of the types package\n// see https://github.com/facebook/react/blob/372ec00c0384cd2089651154ea7c67693ee3f2a5/packages/react/src/ReactLazy.js#L46\ntype LazyComponent<T, P> = {\n $$typeof: symbol | number;\n _payload: P;\n _init: (payload: P) => T;\n};\n\ntype ReactNodeExtended =\n | ReactNode\n | Component<any, any, any>\n | LazyComponent<any, any>\n | ((props: any, deprecatedLegacyContext?: any) => ReactNode);\n\n/**\n * returns true if the value is a primitive, e.g. string, number, boolean\n * @param value - the value to check\n * @returns true if the value is a primitive, false otherwise\n */\nconst isPrimitive = (value: unknown): value is string | number | boolean =>\n typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';\n\n/**\n * returns true if the value is empty, e.g. null or undefined\n * @param value - the value to check\n * @returns true if the value is empty, false otherwise\n */\nconst isEmpty = (value: unknown): value is null | undefined => value === null || value === undefined;\n\n/**\n * returns true if the value is iterable, e.g. an array\n * @param value - the value to check\n * @returns true if the value is iterable, false otherwise\n */\nconst isIterable = (value: unknown): value is Iterable<ReactNode> => Array.isArray(value);\n\n/**\n * returns true if the value is a JSX class element constructor\n * @param value - the value to check\n * @returns true if the value is a JSX class element constructor, false otherwise\n */\nconst isJSXClassElementConstructor = (\n value: unknown\n): value is Exclude<JSXElementConstructor<any>, (props: any, legacyContext: any) => any> =>\n !!value && /^\\s*class\\s+/.test(value.toString());\n\n/**\n * returns true if the value is a lazy exotic component\n * @param value - the value to check\n * @returns true if the value is a lazy exotic component, false otherwise\n */\nconst isLazyExoticComponent = (value: unknown): value is LazyComponent<any, any> =>\n !!value && typeof value === 'object' && '_payload' in value;\n\n/**\n * Transform a React component into a Stencil component for server side rendering. This logic is executed\n * by a React framework e.g. Next.js in an Node.js environment. The function will:\n *\n * - serialize the component (including the Light DOM) into a string (see `toSerializeWithChildren`)\n * - transform the string with the Stencil component into a Declarative Shadow DOM component\n * - parse the declarative shadow DOM component back into a React component\n * - return the React component\n *\n * Note: this code should only be loaded on the server side, as it uses heavy Node.js dependencies,\n * e.g. `react-dom/server`, `html-react-parser` as well as the hydrate module, that when loaded on\n * the client side would increase the bundle size.\n */\nconst createComponentForServerSideRendering = <I extends HTMLElement, E extends EventNames = {}>(\n options: CreateComponentForServerSideRenderingOptions\n) => {\n return (async ({ children, ...props }: StencilProps<I> = {}) => {\n /**\n * ensure we only run on server\n */\n if (!('process' in globalThis) || typeof window !== 'undefined') {\n throw new Error('`createComponent` can only be run on the server');\n }\n\n /**\n * compose element props into a string\n */\n let stringProps = '';\n for (const [key, value] of Object.entries(props)) {\n let propValue = isPrimitive(value)\n ? `\"${value}\"`\n : typeof value !== 'function'\n ? options.serializeProperty(value)\n : undefined;\n\n /**\n * parse the style object into a string\n */\n if (key === 'style' && typeof value === 'object' && value) {\n propValue = `\"${stringifyCSSProperties(value)}\"`;\n }\n\n if (!propValue) {\n continue;\n }\n\n const propName =\n possibleStandardNames[key as keyof typeof possibleStandardNames] || options.properties[key] || key;\n stringProps += ` ${propName}=${propValue}`;\n }\n\n /**\n * Attempt to serialize the components light DOM as it may have an impact on how the Stencil\n * component is being serialized. For example a Stencil component may render certain elements\n * if its light DOM contains other elements.\n */\n let serializedChildren = '';\n const toSerialize = `<${options.tagName}${stringProps} suppressHydrationWarning=\"true\">`;\n const originalConsoleError = console.error;\n try {\n // Ignore potential console errors during serialization (for example if a hook is used, which\n // is not allowed in SSR) as they are not relevant for the user and may cause confusion\n if (!process.env.STENCIL_SSR_DEBUG) {\n console.error = () => {};\n }\n const awaitedChildren = await resolveComponentTypes(children);\n const { renderToString } = await import('react-dom/server');\n serializedChildren = renderToString(awaitedChildren);\n } catch (err: unknown) {\n /**\n * if rendering the light DOM fails, we log a warning and continue to render the component\n */\n if (process.env.STENCIL_SSR_DEBUG) {\n const error = err instanceof Error ? err : new Error('Unknown error');\n console.warn(\n `${LOG_PREFIX} Failed to serialize light DOM for ${toSerialize.slice(0, -1)} />: ${\n error.message\n } - this may impact the hydration of the component`\n );\n }\n } finally {\n console.error = originalConsoleError;\n }\n\n const toSerializeWithChildren = `${toSerialize}${serializedChildren}</${options.tagName}>`;\n\n /**\n * first render the component with `prettyHtml` flag so it makes it easier to\n * access the inner content of the component.\n */\n const { html } = await options.renderToString(toSerializeWithChildren, {\n fullDocument: false,\n serializeShadowRoot: options.serializeShadowRoot ?? 'declarative-shadow-dom',\n prettyHtml: true,\n });\n\n if (!html) {\n throw new Error('No HTML returned from renderToString');\n }\n\n /**\n * cut out the inner content of the component\n */\n const serializedComponentByLine = html.split('\\n');\n const hydrationComment = '<!--r.1-->';\n const isShadowComponent = serializedComponentByLine[1].includes('shadowrootmode=\"open\"');\n let templateContent: undefined | string = undefined;\n if (isShadowComponent) {\n const templateEndTag = ' </template>';\n templateContent = serializedComponentByLine\n .slice(2, serializedComponentByLine.lastIndexOf(templateEndTag))\n .join('\\n')\n .trim();\n }\n\n /**\n * `html-react-parser` is a Node.js dependency so we should make sure to only import it when\n * run on the server and when needed.\n */\n const { default: parse } = await import('html-react-parser');\n const typedParse = parse as unknown as typeof parse.default;\n\n /**\n * Parse the string back into a React component\n */\n const StencilElement = () =>\n typedParse(html, {\n transform(reactNode, domNode) {\n /**\n * only render the component we have been serializing before\n */\n if ('name' in domNode && domNode.name === options.tagName) {\n const props = (reactNode as any).props;\n /**\n * remove the outer tag (e.g. `options.tagName`) so we only have the inner content\n */\n const CustomTag = `${options.tagName}`;\n\n /**\n * if the component is not a shadow component we can render it with the light DOM only\n */\n if (!isShadowComponent) {\n const { children, ...customProps } = props || {};\n const __html = serializedComponentByLine\n /**\n * remove the components outer tags as we want to set the inner content only\n */\n .slice(1, -1)\n /**\n * bring the array back to a string\n */\n .join('\\n')\n .trim()\n /**\n * remove any whitespace between tags that may cause hydration errors\n */\n .replace(/(?<=>)\\s+(?=<)/g, '');\n\n return (\n <CustomTag {...customProps} suppressHydrationWarning={true} dangerouslySetInnerHTML={{ __html }} />\n );\n }\n\n /**\n * return original component with given props and `suppressHydrationWarning` flag and\n * set the template content based on our serialized Stencil component.\n */\n return (\n <CustomTag {...props} suppressHydrationWarning={true}>\n <template\n // @ts-expect-error\n shadowrootmode=\"open\"\n suppressHydrationWarning={true}\n dangerouslySetInnerHTML={{ __html: hydrationComment + templateContent }}\n ></template>\n {children}\n </CustomTag>\n );\n }\n\n return;\n },\n });\n\n return <StencilElement />;\n }) as unknown as ReactWebComponent<I, E>;\n};\n\n/**\n * Resolve the component types for server side rendering.\n *\n * It walks through all component childs and resolves them, e.g. call `createComponentForServerSideRendering` to\n * create a React component which we can pass into `ReactDOMServer.renderToString`. This enables us to include\n * the Light DOM of a component as part of Stencils serialization process.\n *\n * @param children - the children to resolve\n * @returns the resolved children\n */\nasync function resolveComponentTypes(children: ReactNode): Promise<ReactNode> {\n /**\n * If the children are a empty or a primitive we can return them directly\n * e.g. `Hello World` or `42` or `null`\n */\n if (isPrimitive(children) || isEmpty(children)) {\n return children;\n }\n\n /**\n * If the children are not iterable we make them an array, so we can map over them later\n */\n if (!isIterable(children)) {\n children = [children];\n }\n\n return Promise.all(\n Array.from(children).map(async (child) => {\n if (isPrimitive(child) || isEmpty(child)) {\n return child;\n }\n\n if (isIterable(child)) {\n return resolveComponentTypes(child);\n }\n\n // Only ReactElements have type and props properties\n if (!React.isValidElement(child)) {\n return child;\n }\n\n const { type, props } = child as React.ReactElement<object & { children: ReactNode }>;\n\n return {\n ...child,\n props: {\n ...props,\n children: await resolveComponentTypes(props.children),\n },\n type: await resolveType(type, props as any),\n } as ReactNode;\n })\n );\n}\n\n// Resolve the component type to a primitive element type\nconst resolveType = async (type: string | React.JSXElementConstructor<any>, props: any): Promise<ReactNodeExtended> => {\n let resolvedType: ReactNodeExtended = null;\n\n if (typeof type === 'string') {\n // Child is a primitive element like 'div'\n return type;\n } else if (isJSXClassElementConstructor(type)) {\n // Child is a Class Component\n const instance = new type(props);\n resolvedType = instance.render ? instance.render() : instance;\n } else if (isLazyExoticComponent(type)) {\n // Handle React Lazy Component\n // https://github.com/facebook/react/blob/main/packages/react/src/ReactLazy.js\n const payload = type._payload;\n const { deault: lazyComponet } =\n payload._status === -1 // Uninitialized = -1 so we need resolve the promise\n ? await payload._result()\n : payload._result;\n // Now resolve the actual component type of the lazy component\n resolvedType = await resolveType(lazyComponet, props);\n } else if (typeof type !== 'object') {\n // Child is a Function Component because React Server\n // Components can be a Promise we need to await it\n resolvedType = await type(props);\n }\n\n // Recursively resolve the component type until we have a primitive element type\n if (\n !isEmpty(resolvedType) &&\n !isPrimitive(resolvedType) &&\n typeof resolvedType === 'object' &&\n resolvedType !== null &&\n 'type' in resolvedType\n ) {\n resolvedType = await resolveType(resolvedType.type, props);\n }\n\n return resolvedType;\n};\n\n/**\n * Defines a custom element and creates a React component for server side rendering.\n * @public\n */\nexport const createComponent = <I extends HTMLElement, E extends EventNames = {}>({\n hydrateModule,\n properties,\n tagName,\n serializeShadowRoot,\n ...options\n}: {\n hydrateModule: Promise<HydrateModule>;\n properties: Record<string, string>;\n tagName: string;\n serializeShadowRoot?: SerializeShadowRootOptions;\n} & Options<I, E> & { defineCustomElement: () => void }): ReactWebComponent<I, E> => {\n /**\n * If we are running in the browser, we can use the `createComponentWrapper` function\n * to create a React component that can be used in the browser. This allows to import\n * a Stencil component from one source and have a browser and server version of the component.\n */\n if (typeof window !== 'undefined' && createComponentWrapper) {\n return createComponentWrapper<I, E>({\n tagName,\n ...options,\n }) as unknown as ReactWebComponent<I, E>;\n }\n\n /**\n * IIFE to lazy load the `createComponentForServerSideRendering` function while allowing\n * to return the correct type for the `ReactWebComponent`.\n *\n * Note: we want to lazy load the `./ssr` and `hydrateModule` modules to avoid\n * bundling them in the runtime and serving them in the browser.\n */\n return (async (props: WebComponentProps<I>) => {\n const resolvedHydrateModule = await hydrateModule;\n return createComponentForServerSideRendering<I, E>({\n tagName,\n properties,\n renderToString: resolvedHydrateModule.renderToString,\n serializeProperty: resolvedHydrateModule.serializeProperty,\n serializeShadowRoot,\n })(props as any);\n }) as unknown as ReactWebComponent<I, E>;\n};\n"],"names":["unitlessKeys","DEFAULT_UNIT","isCSSPropertyValue","value","camelToKebab","str","match","applyCssUnits","property","unit","isUnitless","unitless","resolvedUnit","stringifyStyleDeclaration","styleDeclaration","options","importantSuffix","_","stringifyCSSProperties","cssProperties","optionsOrImportant","possibleStandardNames","LOG_PREFIX","isPrimitive","isEmpty","isIterable","isJSXClassElementConstructor","isLazyExoticComponent","createComponentForServerSideRendering","children","props","stringProps","key","propValue","propName","serializedChildren","toSerialize","originalConsoleError","awaitedChildren","resolveComponentTypes","renderToString","err","error","toSerializeWithChildren","html","serializedComponentByLine","hydrationComment","isShadowComponent","templateContent","parse","typedParse","StencilElement","reactNode","domNode","CustomTag","customProps","__html","React","child","type","resolveType","resolvedType","instance","payload","lazyComponet","createComponent","hydrateModule","properties","tagName","serializeShadowRoot","createComponentWrapper","resolvedHydrateModule"],"mappings":"imBAAA,IAAIA,EAAe,CACjB,wBAAyB,EACzB,YAAa,EACb,kBAAmB,EACnB,iBAAkB,EAClB,iBAAkB,EAClB,QAAS,EACT,aAAc,EACd,gBAAiB,EACjB,YAAa,EACb,QAAS,EACT,KAAM,EACN,SAAU,EACV,aAAc,EACd,WAAY,EACZ,aAAc,EACd,UAAW,EACX,QAAS,EACT,WAAY,EACZ,YAAa,EACb,aAAc,EACd,WAAY,EACZ,cAAe,EACf,eAAgB,EAChB,gBAAiB,EACjB,UAAW,EACX,cAAe,EACf,aAAc,EACd,iBAAkB,EAClB,WAAY,EACZ,WAAY,EACZ,QAAS,EACT,MAAO,EACP,QAAS,EACT,MAAO,EACP,QAAS,EACT,OAAQ,EACR,OAAQ,EACR,KAAM,EACN,gBAAiB,EAEjB,YAAa,EACb,aAAc,EACd,YAAa,EACb,gBAAiB,EACjB,iBAAkB,EAClB,iBAAkB,EAClB,cAAe,EACf,YAAa,CACf,EC/CIC,EAAe,KACfC,EAAsBC,GAAU,OAAOA,GAAU,UAAY,OAAOA,GAAU,SAClF,SAASC,EAAaC,EAAK,CACzB,OAAOA,EAAI,QAAQ,SAAWC,GAAU,IAAIA,EAAM,YAAa,CAAA,EAAE,CACnE,CAIA,SAASC,EAAcC,EAAUL,EAAOM,EAAOR,EAAc,CAC3D,GAAI,OAAOE,GAAU,UAAY,OAAOA,GAAU,SAChD,MAAM,IAAI,MACR,mEACD,EAEH,M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