astro/packages/integrations/react/server.js

202 lines
5.2 KiB
JavaScript
Raw Permalink Normal View History

import React from 'react';
import ReactDOM from 'react-dom/server';
import StaticHtml from './static-html.js';
import { incrementId } from './context.js';
import opts from 'astro:react:opts';
2022-06-23 15:12:46 +00:00
const slotName = (str) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase());
const reactTypeof = Symbol.for('react.element');
function errorIsComingFromPreactComponent(err) {
2022-04-02 20:15:41 +00:00
return (
err.message &&
(err.message.startsWith("Cannot read property '__H'") ||
err.message.includes("(reading '__H')"))
);
}
async function check(Component, props, children) {
// Note: there are packages that do some unholy things to create "components".
// Checking the $$typeof property catches most of these patterns.
if (typeof Component === 'object') {
return Component['$$typeof'].toString().slice('Symbol('.length).startsWith('react');
}
if (typeof Component !== 'function') return false;
if (Component.prototype != null && typeof Component.prototype.render === 'function') {
return React.Component.isPrototypeOf(Component) || React.PureComponent.isPrototypeOf(Component);
}
let error = null;
let isReactComponent = false;
function Tester(...args) {
try {
const vnode = Component(...args);
if (vnode && vnode['$$typeof'] === reactTypeof) {
isReactComponent = true;
}
} catch (err) {
if (!errorIsComingFromPreactComponent(err)) {
error = err;
}
}
return React.createElement('div');
}
await renderToStaticMarkup(Tester, props, children, {});
if (error) {
throw error;
}
return isReactComponent;
}
async function getNodeWritable() {
let nodeStreamBuiltinModuleName = 'stream';
2022-08-30 07:25:34 +00:00
let { Writable } = await import(/* @vite-ignore */ nodeStreamBuiltinModuleName);
return Writable;
}
function needsHydration(metadata) {
// Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
return metadata.astroStaticSlot ? !!metadata.hydrate : true;
}
async function renderToStaticMarkup(Component, props, { default: children, ...slotted }, metadata) {
let prefix;
if (this && this.result) {
2023-05-04 14:25:03 +00:00
prefix = incrementId(this.result);
}
const attrs = { prefix };
delete props['class'];
const slots = {};
for (const [key, value] of Object.entries(slotted)) {
const name = slotName(key);
slots[name] = React.createElement(StaticHtml, {
hydrate: needsHydration(metadata),
value,
2023-05-17 14:20:24 +00:00
name,
});
}
// Note: create newProps to avoid mutating `props` before they are serialized
2022-06-23 15:12:46 +00:00
const newProps = {
...props,
...slots,
2022-06-23 15:12:46 +00:00
};
const newChildren = children ?? props.children;
if (children && opts.experimentalReactChildren) {
2023-08-16 17:44:01 +00:00
const convert = await import('./vnode-children.js').then((mod) => mod.default);
newProps.children = convert(children);
} else if (newChildren != null) {
newProps.children = React.createElement(StaticHtml, {
hydrate: needsHydration(metadata),
2023-05-17 14:20:24 +00:00
value: newChildren,
});
}
const vnode = React.createElement(Component, newProps);
const renderOptions = {
2023-05-04 14:25:03 +00:00
identifierPrefix: prefix,
};
let html;
if (metadata?.hydrate) {
2022-04-21 16:11:09 +00:00
if ('renderToReadableStream' in ReactDOM) {
html = await renderToReadableStreamAsync(vnode, renderOptions);
} else {
html = await renderToPipeableStreamAsync(vnode, renderOptions);
}
} else {
2022-04-21 16:11:09 +00:00
if ('renderToReadableStream' in ReactDOM) {
html = await renderToReadableStreamAsync(vnode, renderOptions);
} else {
html = await renderToStaticNodeStreamAsync(vnode, renderOptions);
}
}
return { html, attrs };
}
async function renderToPipeableStreamAsync(vnode, options) {
const Writable = await getNodeWritable();
let html = '';
return new Promise((resolve, reject) => {
let error = undefined;
let stream = ReactDOM.renderToPipeableStream(vnode, {
...options,
onError(err) {
error = err;
reject(error);
},
onAllReady() {
2022-04-21 16:11:09 +00:00
stream.pipe(
new Writable({
write(chunk, _encoding, callback) {
html += chunk.toString('utf-8');
callback();
},
destroy() {
resolve(html);
},
})
);
},
});
});
}
async function renderToStaticNodeStreamAsync(vnode, options) {
const Writable = await getNodeWritable();
let html = '';
return new Promise((resolve, reject) => {
let stream = ReactDOM.renderToStaticNodeStream(vnode, options);
2022-09-20 13:40:04 +00:00
stream.on('error', (err) => {
reject(err);
});
2022-04-21 16:11:09 +00:00
stream.pipe(
new Writable({
write(chunk, _encoding, callback) {
html += chunk.toString('utf-8');
callback();
},
destroy() {
resolve(html);
},
})
);
});
}
/**
* Use a while loop instead of "for await" due to cloudflare and Vercel Edge issues
* See https://github.com/facebook/react/issues/24169
*/
async function readResult(stream) {
2022-09-08 16:32:36 +00:00
const reader = stream.getReader();
let result = '';
const decoder = new TextDecoder('utf-8');
while (true) {
const { done, value } = await reader.read();
if (done) {
2022-09-08 16:32:36 +00:00
if (value) {
result += decoder.decode(value);
} else {
// This closes the decoder
decoder.decode(new Uint8Array());
}
2022-09-08 16:32:36 +00:00
return result;
}
2022-09-08 16:32:36 +00:00
result += decoder.decode(value, { stream: true });
}
}
async function renderToReadableStreamAsync(vnode, options) {
return await readResult(await ReactDOM.renderToReadableStream(vnode, options));
}
export default {
check,
renderToStaticMarkup,
supportsAstroStaticSlot: true,
};