UNPKG

@stencil/react-output-target

Version:

React output target for @stencil/core components.

486 lines (485 loc) • 16 kB
import l, { Fragment as G } from "react"; import { c as C } from "./create-component-ICzm58MY.js"; var V = { animationIterationCount: 1, aspectRatio: 1, borderImageOutset: 1, borderImageSlice: 1, borderImageWidth: 1, boxFlex: 1, boxFlexGroup: 1, boxOrdinalGroup: 1, columnCount: 1, columns: 1, flex: 1, flexGrow: 1, flexPositive: 1, flexShrink: 1, flexNegative: 1, flexOrder: 1, gridRow: 1, gridRowEnd: 1, gridRowSpan: 1, gridRowStart: 1, gridColumn: 1, gridColumnEnd: 1, gridColumnSpan: 1, gridColumnStart: 1, msGridRow: 1, msGridRowSpan: 1, msGridColumn: 1, msGridColumnSpan: 1, fontWeight: 1, lineHeight: 1, opacity: 1, order: 1, orphans: 1, scale: 1, tabSize: 1, widows: 1, zIndex: 1, zoom: 1, WebkitLineClamp: 1, // SVG-related properties fillOpacity: 1, floodOpacity: 1, stopOpacity: 1, strokeDasharray: 1, strokeDashoffset: 1, strokeMiterlimit: 1, strokeOpacity: 1, strokeWidth: 1 }, E = "px", X = (e) => typeof e == "number" || typeof e == "string"; function B(e) { return e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`); } function Y(e, t, n = E) { if (typeof t != "string" && typeof t != "number") throw new Error( "Invalid input: value of 'cssProperties' must be string or number." ); const o = V[e] === 1; if (typeof t == "string" || t === 0 || o) return `${t}`; const r = (typeof n == "string" ? n : n[e]) || E; return `${t}${r}`; } function K(e, t) { if (typeof e != "object" || e === null) throw new TypeError( `[stringifyStyleDeclaration]: Expected 'styleDeclaration' to be a non-null object, but received ${e} (type:${typeof e}).` ); const n = t != null && t.important ? "!important" : ""; return Object.entries(e).filter(([o, r]) => X(r)).map( ([o, r]) => `${B(o)}:${Y( o, r, t == null ? void 0 : t.unit )}${n};` ).join(""); } function Z(e, t = !1) { if (typeof e != "object" || e === null) throw new TypeError( `[stringifyCSSProperties]: Expected 'cssProperties' to be a non-null object, but received ${e} (type:${typeof e}).` ); return K(e, typeof t == "boolean" ? { important: t } : t); } const J = { acceptCharset: "accept-charset", accessKey: "accesskey", allowFullScreen: "allowfullscreen", autoCapitalize: "autocapitalize", autoComplete: "autocomplete", autoCorrect: "autocorrect", autoFocus: "autofocus", autoPlay: "autoplay", autoSave: "autosave", cellPadding: "cellpadding", cellSpacing: "cellspacing", charSet: "charset", className: "class", classID: "classid", colSpan: "colspan", contentEditable: "contenteditable", contextMenu: "contextmenu", controlsList: "controlslist", crossOrigin: "crossorigin", dangerouslySetInnerHTML: "dangerouslysetinnerhtml", dateTime: "datetime", defaultChecked: "defaultchecked", defaultValue: "defaultvalue", disablePictureInPicture: "disablepictureinpicture", disableRemotePlayback: "disableremoteplayback", encType: "enctype", enterKeyHint: "enterkeyhint", fetchPriority: "fetchpriority", htmlFor: "for", formMethod: "formmethod", formAction: "formaction", formEncType: "formenctype", formNoValidate: "formnovalidate", formTarget: "formtarget", frameBorder: "frameborder", hrefLang: "hreflang", httpEquiv: "http-equiv", imageSizes: "imagesizes", imageSrcSet: "imagesrcset", inputMode: "inputmode", itemID: "itemid", itemProp: "itemprop", itemRef: "itemref", itemScope: "itemscope", itemType: "itemtype", keyParams: "keyparams", keyType: "keytype", marginWidth: "marginwidth", marginHeight: "marginheight", maxLength: "maxlength", mediaGroup: "mediagroup", noModule: "nomodule", noValidate: "novalidate", playsInline: "playsinline", radioGroup: "radiogroup", readOnly: "readonly", referrerPolicy: "referrerpolicy", rowSpan: "rowspan", spellCheck: "spellcheck", srcDoc: "srcdoc", srcLang: "srclang", srcSet: "srcset", tabIndex: "tabindex", useMap: "usemap", accentHeight: "accent-height", alignmentBaseline: "alignment-baseline", arabicForm: "arabic-form", attributeName: "attributename", attributeType: "attributetype", autoReverse: "autoreverse", baseFrequency: "basefrequency", baselineShift: "baseline-shift", baseProfile: "baseprofile", calcMode: "calcmode", capHeight: "cap-height", clipPath: "clip-path", clipPathUnits: "clippathunits", clipRule: "clip-rule", colorInterpolation: "color-interpolation", colorInterpolationFilters: "color-interpolation-filters", colorProfile: "color-profile", colorRendering: "color-rendering", contentScriptType: "contentscripttype", contentStyleType: "contentstyletype", diffuseConstant: "diffuseconstant", dominantBaseline: "dominant-baseline", enableBackground: "enable-background", externalResourcesRequired: "externalresourcesrequired", fillOpacity: "fill-opacity", fillRule: "fill-rule", filterRes: "filterres", filterUnits: "filterunits", floodOpacity: "flood-opacity", floodColor: "flood-color", fontFamily: "font-family", fontSize: "font-size", fontSizeAdjust: "font-size-adjust", fontStretch: "font-stretch", fontStyle: "font-style", fontVariant: "font-variant", fontWeight: "font-weight", glyphName: "glyph-name", glyphOrientationHorizontal: "glyph-orientation-horizontal", glyphOrientationVertical: "glyph-orientation-vertical", gradientTransform: "gradienttransform", gradientUnits: "gradientunits", horizAdvX: "horiz-adv-x", horizOriginX: "horiz-origin-x", imageRendering: "image-rendering", kernelMatrix: "kernelmatrix", kernelUnitLength: "kernelunitlength", keyPoints: "keypoints", keySplines: "keysplines", keyTimes: "keytimes", lengthAdjust: "lengthadjust", letterSpacing: "letter-spacing", lightingColor: "lighting-color", limitingConeAngle: "limitingconeangle", markerEnd: "marker-end", markerHeight: "markerheight", markerMid: "marker-mid", markerStart: "marker-start", markerUnits: "markerunits", markerWidth: "markerwidth", maskContentUnits: "maskcontentunits", maskUnits: "maskunits", numOctaves: "numoctaves", overlinePosition: "overline-position", overlineThickness: "overline-thickness", paintOrder: "paint-order", panose1: "panose-1", pathLength: "pathlength", patternContentUnits: "patterncontentunits", patternTransform: "patterntransform", patternUnits: "patternunits", pointerEvents: "pointer-events", pointsAtX: "pointsatx", pointsAtY: "pointsaty", pointsAtZ: "pointsatz", preserveAlpha: "preservealpha", preserveAspectRatio: "preserveaspectratio", primitiveUnits: "primitiveunits", refX: "refx", refY: "refy", renderingIntent: "rendering-intent", repeatCount: "repeatcount", repeatDur: "repeatdur", requiredExtensions: "requiredextensions", requiredFeatures: "requiredfeatures", shapeRendering: "shape-rendering", slot: "slot", specularConstant: "specularconstant", specularExponent: "specularexponent", spreadMethod: "spreadmethod", startOffset: "startoffset", stdDeviation: "stddeviation", stitchTiles: "stitchtiles", stopColor: "stop-color", stopOpacity: "stop-opacity", strikethroughPosition: "strikethrough-position", strikethroughThickness: "strikethrough-thickness", strokeDasharray: "stroke-dasharray", strokeDashoffset: "stroke-dashoffset", strokeLinecap: "stroke-linecap", strokeLinejoin: "stroke-linejoin", strokeMiterlimit: "stroke-miterlimit", strokeWidth: "stroke-width", strokeOpacity: "stroke-opacity", suppressContentEditableWarning: "suppresscontenteditablewarning", suppressHydrationWarning: "suppresshydrationwarning", surfaceScale: "surfacescale", systemLanguage: "systemlanguage", tableValues: "tablevalues", targetX: "targetx", targetY: "targety", textAnchor: "text-anchor", textDecoration: "text-decoration", textLength: "textlength", textRendering: "text-rendering", transformOrigin: "transform-origin", underlinePosition: "underline-position", underlineThickness: "underline-thickness", unicodeBidi: "unicode-bidi", unicodeRange: "unicode-range", unitsPerEm: "units-per-em", vectorEffect: "vector-effect", vertAdvY: "vert-adv-y", vertOriginX: "vert-origin-x", vertOriginY: "vert-origin-y", wordSpacing: "word-spacing", writingMode: "writing-mode", xChannelSelector: "xchannelselector", xHeight: "x-height", xlinkActuate: "xlink:actuate", xlinkArcrole: "xlink:arcrole", xlinkHref: "xlink:href", xlinkRole: "xlink:role", xlinkShow: "xlink:show", xlinkTitle: "xlink:title", xlinkType: "xlink:type", xmlBase: "xml:base", xmlLang: "xml:lang", xmlnsXlink: "xmlns:xlink", yChannelSelector: "ychannelselector", zoomAndPan: "zoomandpan" }, Q = "[react-output-target]", ee = (e) => typeof e.resetReusableWindows == "function", x = Symbol("stencil-react-ssr-options"), z = (e, t) => { const n = {}, o = {}; for (const [r, i] of Object.entries(e)) { if (typeof i == "boolean" && i === !1) continue; const c = J[r] || t[r] || r; if (r === "style" && typeof i == "object" && i) { n[c] = i; continue; } k(i) ? n[c] = i : o[r] = i; } return { attributes: n, complexProps: o }; }, te = (e) => typeof e == "function" && x in e, re = (e) => ({ children: t, ...n }) => { const { attributes: o } = z(n, e.properties), r = e.transformTag ?? (g == null ? void 0 : g.transformTag), i = r ? r(e.tagName) : e.tagName; return l.createElement(i, { ...o, suppressHydrationWarning: !0 }, t); }, R = (e) => "name" in e && "attribs" in e, ne = (e, t, n) => { const i = n(e, { withStartIndices: !0, withEndIndices: !0 }).find((u) => R(u) && t.includes(u.name)); if (!i) throw new Error(`Could not find <${t[0]}> in the HTML returned from renderToString`); const c = (u) => u.length === 0 ? "" : e.slice(u[0].startIndex, u[u.length - 1].endIndex + 1), d = c([i]), p = i.children.find(R); return (p == null ? void 0 : p.name) !== "template" || p.attribs.shadowrootmode !== "open" ? { html: d, lightDom: c(i.children), template: void 0 } : { html: d, lightDom: void 0, template: { delegatesFocus: "shadowrootdelegatesfocus" in p.attribs, content: c(p.children) } }; }, oe = (e) => e.replace(/&/g, "&amp;").replace(/"/g, "&quot;"), k = (e) => typeof e == "string" || typeof e == "number" || typeof e == "boolean", b = (e) => e == null, P = (e) => Array.isArray(e), ie = (e) => !!e && /^\s*class\s+/.test(e.toString()), ae = (e) => !!e && typeof e == "object" && "_payload" in e, se = (e) => !!e && typeof e == "object" && "$$typeof" in e && ("render" in e || "type" in e && "compare" in e), le = (e) => async ({ children: t, ...n } = {}) => { if (!("process" in globalThis) || typeof window < "u") throw new Error("`createComponentForServerSideRendering` can only be run on the server"); const { attributes: o, complexProps: r } = z(n, e.properties); let i = ""; for (const [s, a] of Object.entries(o)) { const f = typeof a == "object" ? Z(a) : a; i += ` ${s}="${oe(String(f))}"`; } let c = ""; const d = e.transformTag ? e.transformTag(e.tagName) : e.tagName, p = `<${d}${i} suppressHydrationWarning="true">`, u = console.error; try { process.env.STENCIL_SSR_DEBUG || (console.error = () => { }); const s = await S(t), { renderToString: a } = await import("react-dom/server"); c = a(s).replace(/\n\s+/g, ""); } catch (s) { if (process.env.STENCIL_SSR_DEBUG) { const a = s instanceof Error ? s : new Error("Unknown error"); console.warn( `${Q} Failed to serialize light DOM for ${p.slice(0, -1)} />: ${a.message} - this may impact the hydration of the component` ); } } finally { console.error = u; } const O = `${p}${c}</${d}>`, { html: T, styles: v } = await e.renderToString(O, { fullDocument: !1, serializeShadowRoot: e.serializeShadowRoot ?? "declarative-shadow-dom", ...e.reuseWindow && { reuseWindow: !0 }, ...Object.keys(r).length > 0 && { beforeHydrate: (s) => { const a = s.querySelector(d); if (a) for (const [f, h] of Object.entries(r)) a[f] = h; } } }); if (!T) throw new Error("No HTML returned from renderToString"); const { default: $, htmlToDOM: H } = await import("html-react-parser"), I = $, { html: M, lightDom: L, template: m } = ne( T, [d, e.tagName], H ), N = m !== void 0, W = !!(m != null && m.delegatesFocus), j = "<!--r.1-->", A = (m == null ? void 0 : m.content) ?? "", _ = () => I(M, { transform(s, a) { if ("name" in a && (a.name === d || a.name === e.tagName)) { const f = s.props, h = `${d}`; if (!N) { const { children: ce, ...F } = f || {}, D = L ?? "", U = v.length > 0 && v.map((y, q) => /* @__PURE__ */ l.createElement( "style", { href: `stencil-${y.id || e.tagName}`, key: y.id || q, id: y.id, precedence: "stencil", suppressHydrationWarning: !0, dangerouslySetInnerHTML: { __html: y.content || "" } } )); return /* @__PURE__ */ l.createElement(G, null, U, /* @__PURE__ */ l.createElement(h, { ...F, suppressHydrationWarning: !0, dangerouslySetInnerHTML: { __html: D } })); } return /* @__PURE__ */ l.createElement(h, { ...f, suppressHydrationWarning: !0 }, /* @__PURE__ */ l.createElement( "template", { shadowrootmode: "open", ...W ? { shadowrootdelegatesfocus: "" } : {}, suppressHydrationWarning: !0, dangerouslySetInnerHTML: { __html: j + A } } ), t); } } }); return /* @__PURE__ */ l.createElement(_, null); }; async function S(e) { return k(e) || b(e) ? e : (P(e) || (e = [e]), Promise.all( Array.from(e).map(async (t) => { if (k(t) || b(t)) return t; if (P(t)) return S(t); if (!l.isValidElement(t)) return t; const { type: n, props: o } = t, r = await w(n, o); return l.isValidElement(r) ? r : { ...t, props: { ...o, children: await S(o.children) }, type: r }; }) )); } const w = async (e, t) => { let n = null; if (te(e)) return re(e[x]); if (typeof e == "string") return e; if (ie(e)) { const o = new e(t, void 0); n = o.render ? o.render() : o; } else if (ae(e)) { const o = e._payload; let r; if (typeof e._init == "function" && o._result === void 0) { const i = await e._init(o); r = (i == null ? void 0 : i.default) ?? i; } else { const { default: i } = o._status === -1 ? await o._result() : o._result; r = i; } n = await w(r, t); } else { if (se(e)) return e; typeof e != "object" && (n = await e(t)); } return !b(n) && !k(n) && l.isValidElement(n) && (n = await w(n.type, t)), n; }; let g = null; const ue = (e) => { if (typeof window < "u") { if (e.clientModule) return e.clientModule; if (C) return C({ tagName: e.tagName, properties: e.properties }); } const t = async (n) => { if (!e.hydrateModule) throw new Error( "`hydrateModule` is required when rendering a Stencil component on the server. This indicates a misconfiguration of the Stencil React output target." ); let o = !1; g || (g = await e.hydrateModule, o = !0); const r = g; if (e.getTagTransformer && o) { const i = e.getTagTransformer(); i && r.setTagTransformer(i); } return e.transformTag = r.transformTag, le({ renderToString: r.renderToString, reuseWindow: ee(r), ...e })(n); }; return t[x] = e, t; }; export { ue as createComponent, ne as splitRenderedComponent }; //# sourceMappingURL=ssr.js.map