feat: more advanced prop serializer for islands (#1224)

This commit adds support for an advanced (de)serializer that is used
for page state (island props and plugin state). This new serializer
supports maintaining references (thus supporting circular objects,
and multi-referenced objects).

This is a pre-requisite for allowing to pass signals, JSX, Uint8Arrays,
Date, and many other "advanced" values.
This commit is contained in:
Luca Casonato
2023-05-31 10:12:07 +02:00
committed by GitHub
parent 060e2bb50d
commit a6852fa58f
16 changed files with 335 additions and 77 deletions
+36
View File
@@ -0,0 +1,36 @@
// Run `deno run -A npm:esbuild --minify src/runtime/deserializer.ts` to minify
// this file. It is embedded into src/server/deserializer_code.ts.
export const KEY = "_f";
export function deserialize(str: string): unknown {
function reviver(this: unknown, _key: string, value: unknown): unknown {
if (typeof value === "object" && value && KEY in value) {
// deno-lint-ignore no-explicit-any
const v: any = value;
if (v[KEY] === "l") {
const val = v.v;
val[KEY] = v.k;
return val;
}
throw new Error(`Unknown key: ${v[KEY]}`);
}
return value;
}
const { v, r } = JSON.parse(str, reviver);
const references = (r ?? []) as [string[], ...string[][]][];
for (const [targetPath, ...refPaths] of references) {
const target = targetPath.reduce((o, k) => k === null ? o : o[k], v);
for (const refPath of refPaths) {
if (refPath.length === 0) throw new Error("Invalid reference");
// set the reference to the target object
const parent = refPath.slice(0, -1).reduce(
(o, k) => k === null ? o : o[k],
v,
);
parent[refPath.at(-1)!] = target;
}
}
return v;
}
+1
View File
@@ -0,0 +1 @@
export { deserialize } from "../deserializer.ts";
@@ -1,5 +1,5 @@
import { ComponentType, h, options, render } from "preact";
import { assetHashingHook } from "./utils.ts";
import { assetHashingHook } from "../utils.ts";
function createRootFragment(
parent: Element,
+2
View File
@@ -0,0 +1,2 @@
import "preact/debug";
export * from "./main.ts";
-2
View File
@@ -1,2 +0,0 @@
import "preact/debug";
export { revive } from "./main.ts";