Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: streaming serializer #275

Merged
merged 4 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/dom-expressions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
},
"peerDependencies": {
"csstype": "^3.0",
"seroval": "^0.7.0"
"seroval": "^0.10.1"
},
"devDependencies": {
"babel-plugin-jsx-dom-expressions": "^0.36.10",
"csstype": "^3.1",
"seroval": "^0.7.0"
"seroval": "^0.10.1"
}
}
4 changes: 3 additions & 1 deletion packages/dom-expressions/src/serializer.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export default function stringify(root: unknown): string;
import { Serializer } from "seroval";

export default function createSerializer(onData: (value: string) => void): Serializer;
19 changes: 15 additions & 4 deletions packages/dom-expressions/src/serializer.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import { serialize, Feature } from "seroval"
import { Feature, Serializer, CROSS_REFERENCE_HEADER } from "seroval"

const ES2017FLAG =
Feature.AggregateError // ES2021
| Feature.BigInt // ES2020
| Feature.BigIntTypedArray // ES2020;

export default function stringify(data) {
return serialize(data, { disabledFeatures: ES2017FLAG });
}
const GLOBAL_IDENTIFIER = '$HY.r'; // TODO this is a pending name

export default function createSerializer(onData) {
return new Serializer({
globalIdentifier: GLOBAL_IDENTIFIER,
disabledFeatures: ES2017FLAG,
onData,
});
}

// TODO
export function getHeaderScript() {
return CROSS_REFERENCE_HEADER;
}
47 changes: 23 additions & 24 deletions packages/dom-expressions/src/server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Aliases, BooleanAttributes, ChildProperties } from "./constants";
import { sharedConfig, root } from "rxcore";
import stringify from "./serializer";
export { stringify };
import createSerializer from "./serializer";
export { createSerializer };
export { createComponent } from "rxcore";

// Based on https://github.com/WebReflection/domtagger/blob/master/esm/sanitizer.js
Expand All @@ -11,17 +11,16 @@ const REPLACE_SCRIPT = `function $df(e,n,t,o,d){if(t=document.getElementById(e),

export function renderToString(code, options = {}) {
let scripts = "";
const serializer = createSerializer((script) => scripts += script);
sharedConfig.context = {
id: options.renderId || "",
count: 0,
suspense: {},
lazy: {},
assets: [],
nonce: options.nonce,
writeResource(id, p, error) {
if (sharedConfig.context.noHydrate) return;
if (error) return (scripts += `_$HY.set("${id}", ${stringify(p)});`);
scripts += `_$HY.set("${id}", ${stringify(p)});`;
writeResource(id, p) {
!sharedConfig.context.noHydrate && serializer.write(id, p);
}
};
let html = root(d => {
Expand All @@ -31,6 +30,7 @@ export function renderToString(code, options = {}) {
sharedConfig.context.noHydrate = true;
html = injectAssets(sharedConfig.context.assets, html);
if (scripts.length) html = injectScripts(html, scripts, options.nonce);
serializer.close();
return html;
}

Expand All @@ -50,6 +50,9 @@ export function renderToStream(code, options = {}) {
let { nonce, onCompleteShell, onCompleteAll, renderId } = options;
let dispose;
const blockingResources = [];
const serializer = createSerializer((value) => {
// TODO
});
const registry = new Map();
const dedupe = new WeakMap();
const checkEnd = () => {
Expand Down Expand Up @@ -118,18 +121,21 @@ export function renderToStream(code, options = {}) {
);
},
writeResource(id, p, error, wait) {
// TODO this is a draft
const serverOnly = sharedConfig.context.noHydrate;
if (error) return !serverOnly && pushTask(serializeSet(dedupe, id, p));
if (!p || typeof p !== "object" || !("then" in p))
return !serverOnly && pushTask(serializeSet(dedupe, id, p));
if (!firstFlushed) wait && blockingResources.push(p);
else !serverOnly && pushTask(`_$HY.init("${id}")`);
if (serverOnly) return;
p.then(d => {
!completed && pushTask(serializeSet(dedupe, id, d));
}).catch(() => {
!completed && pushTask(`_$HY.set("${id}", {})`);
});
if (error) return !serverOnly && serializer.write(id, p);
if (!firstFlushed) {
if (wait) {
blockingResources.push(p);
!serverOnly && p.then((d) => {
serializer.write(id, d);
}).catch(() => {
serializer.write(id, {});
});
}
} else {
!serverOnly && serializer.write(p);
}
},
registerFragment(key) {
if (!registry.has(key)) {
Expand Down Expand Up @@ -512,13 +518,6 @@ function waitForFragments(registry, key) {
return false;
}

function serializeSet(registry, key, value) {
const exist = registry.get(value);
if (exist) return `_$HY.set("${key}", _$HY.r["${exist}"][0])`;
value !== null && typeof value === "object" && registry.set(value, key);
return `_$HY.set("${key}", ${stringify(value)})`;
}

function replacePlaceholder(html, key, value) {
const marker = `<template id="pl-${key}">`;
const close = `<!--pl-${key}-->`;
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading