major: import Fresh 2.0 code (#2449)

🎉
This commit is contained in:
Marvin Hagemeister
2024-05-24 09:40:08 +02:00
committed by GitHub
parent 990357629e
commit 287929e4d2
958 changed files with 15794 additions and 28287 deletions
+7
View File
@@ -0,0 +1,7 @@
export const UNDEFINED = -1;
export const NULL = -2;
export const NAN = -3;
export const INFINITY_POS = -4;
export const INFINITY_NEG = -5;
export const ZERO_NEG = -6;
export const HOLE = -7;
+54
View File
@@ -0,0 +1,54 @@
import { expect } from "@std/expect";
import { parse } from "./parse.ts";
import { stringify } from "./stringify.ts";
import { Signal, signal } from "@preact/signals";
Deno.test("custom parse - Point", () => {
class Point {
constructor(public x: number, public y: number) {
this.x = x;
this.y = y;
}
}
const str = stringify(new Point(30, 40), {
Point: (value) => value instanceof Point ? [value.x, value.y] : undefined,
});
expect(str).toEqual('[["Point",1],[2,3],30,40]');
const point = parse(str, {
Point: ([x, y]: [number, number]) => new Point(x, y),
});
expect(point).toEqual(new Point(30, 40));
});
Deno.test("custom parse - Signals", () => {
const res = parse<Signal>('[["Signal",1],2]', {
Signal: (value) => signal(value),
});
expect(res).toBeInstanceOf(Signal);
expect(res.peek()).toEqual(2);
});
Deno.test("custom stringify - Signals", () => {
const s = signal(2);
expect(stringify(s, {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? s2.peek() : undefined;
},
})).toEqual(
'[["Signal",1],2]',
);
});
Deno.test("custom stringify - referenced Signals", () => {
const s = signal(2);
expect(stringify([s, s], {
Signal: (s2: unknown) => {
return s2 instanceof Signal ? s2.peek() : undefined;
},
})).toEqual(
'[[1,1],["Signal",2],2]',
);
});
+193
View File
@@ -0,0 +1,193 @@
import {
HOLE,
INFINITY_NEG,
INFINITY_POS,
NAN,
NULL,
UNDEFINED,
ZERO_NEG,
} from "./constants.ts";
// deno-lint-ignore no-explicit-any
export type CustomParser = Record<string, (value: any) => unknown>;
export function parse<T = unknown>(
value: string,
custom?: CustomParser | undefined,
): T {
const data = JSON.parse(value);
const hydrated = new Array(data.length);
// deno-lint-ignore no-explicit-any
unpack(data, hydrated, 0, custom) as any;
return hydrated[0];
}
function unpack(
arr: unknown[],
hydrated: unknown[],
idx: number,
custom: CustomParser | undefined,
): void {
if (idx in hydrated) return;
const current = arr[idx];
if (typeof current === "number") {
switch (current) {
case UNDEFINED:
hydrated[idx] = undefined;
return;
case NULL:
hydrated[idx] = null;
return;
case NAN:
hydrated[idx] = NaN;
return;
case INFINITY_POS:
hydrated[idx] = Infinity;
return;
case INFINITY_NEG:
hydrated[idx] = -Infinity;
return;
case ZERO_NEG:
hydrated[idx] = -0;
return;
default:
hydrated[idx] = current;
return;
}
} else if (
typeof current === "string" || typeof current === "boolean" ||
current === null
) {
hydrated[idx] = current;
return;
} else if (Array.isArray(current)) {
if (current.length > 0 && typeof current[0] === "string") {
const name = current[0];
if (custom !== undefined && name in custom) {
const fn = custom[name];
const ref = current[1];
unpack(arr, hydrated, ref, custom);
const value = hydrated[ref];
hydrated[idx] = fn(value);
return;
}
switch (name) {
case "BigInt":
hydrated[idx] = BigInt(current[1]);
return;
case "Date":
hydrated[idx] = new Date(current[1]);
return;
case "RegExp":
hydrated[idx] = new RegExp(current[1], current[2]);
return;
case "Set": {
const set = new Set();
for (let i = 0; i < current[1].length; i++) {
const ref = current[1][i];
unpack(arr, hydrated, ref, custom);
set.add(hydrated[ref]);
}
hydrated[idx] = set;
return;
}
case "Map": {
const set = new Map();
for (let i = 0; i < current[1].length; i++) {
const refKey = current[1][i++];
unpack(arr, hydrated, refKey, custom);
const refValue = current[1][i];
unpack(arr, hydrated, refValue, custom);
set.set(hydrated[refKey], hydrated[refValue]);
}
hydrated[idx] = set;
return;
}
case "Uint8Array":
hydrated[idx] = b64decode(current[1]);
return;
}
} else {
const actual = new Array(current.length);
hydrated[idx] = actual;
for (let i = 0; i < current.length; i++) {
const ref = current[i];
if (ref < 0) {
switch (ref) {
case UNDEFINED:
actual[i] = undefined;
break;
case NULL:
actual[i] = null;
break;
case NAN:
actual[i] = NaN;
break;
case INFINITY_POS:
actual[i] = Infinity;
break;
case INFINITY_NEG:
actual[i] = -Infinity;
break;
case ZERO_NEG:
actual[i] = -0;
break;
case HOLE:
continue;
}
} else {
unpack(arr, hydrated, ref, custom);
actual[i] = hydrated[ref];
}
}
}
} else if (typeof current === "object") {
const actual: Record<string, unknown> = {};
hydrated[idx] = actual;
const keys = Object.keys(current);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// deno-lint-ignore no-explicit-any
const ref = (current as any)[key];
if (ref < 0) {
switch (ref) {
case UNDEFINED:
actual[key] = undefined;
break;
case NULL:
actual[key] = null;
break;
case NAN:
actual[key] = NaN;
break;
case INFINITY_POS:
actual[key] = Infinity;
break;
case INFINITY_NEG:
actual[key] = -Infinity;
break;
case ZERO_NEG:
actual[key] = -0;
break;
}
} else {
unpack(arr, hydrated, ref, custom);
actual[key] = hydrated[ref];
}
}
}
}
function b64decode(b64: string): Uint8Array {
const binString = atob(b64);
const size = binString.length;
const bytes = new Uint8Array(size);
for (let i = 0; i < size; i++) {
bytes[i] = binString.charCodeAt(i);
}
return bytes;
}
+99
View File
@@ -0,0 +1,99 @@
import { expect } from "@std/expect";
import { parse } from "./parse.ts";
Deno.test("parse - json", () => {
expect(parse("[2]")).toEqual(2);
expect(parse('["abc"]')).toEqual("abc");
expect(parse("[true]")).toEqual(true);
expect(parse("[false]")).toEqual(false);
expect(parse("[[1,2,3],1,2,3]")).toEqual([1, 2, 3]);
expect(parse('[{"a":1,"b":-2,"c":2},1,[-2]]')).toEqual({
a: 1,
b: null,
c: [null],
});
});
Deno.test("parse - hole array", () => {
expect(parse("[[1,-7,2],1,3]")).toEqual([1, , 3]);
});
Deno.test("parse - undefined", () => {
expect(parse("[-1]")).toEqual(undefined);
});
Deno.test("parse - Infinity", () => {
expect(parse("[-4]")).toEqual(Infinity);
expect(parse("[-5]")).toEqual(-Infinity);
});
Deno.test("parse - NaN", () => {
expect(parse("[-3]")).toEqual(NaN);
});
Deno.test("parse - -0", () => {
expect(parse("[-6]")).toEqual(-0);
});
Deno.test("parse - bigint", () => {
const n = BigInt(9007199254740991);
expect(parse('[["BigInt","9007199254740991"]]')).toEqual(
n,
);
});
Deno.test("parse - Set", () => {
const res = parse('[["Set",[1,2]],1,{"foo":1}]');
expect(res).toEqual(
new Set([1, { foo: 1 }]),
);
});
Deno.test("parse - Map", () => {
expect(parse('[["Map",[1,2,3,4]],1,{"foo":1},2,3]'))
.toEqual(
new Map<number, unknown>([[1, { foo: 1 }], [2, 3]]),
);
});
Deno.test("parse - Date", () => {
const date = new Date("1990-05-31");
expect(parse('[["Date","1990-05-31T00:00:00.000Z"]]')).toEqual(
date,
);
});
Deno.test("parse - RegExp", () => {
let reg = /foo["]/;
expect(parse('[["RegExp","foo[\\"]", ""]]')).toEqual(reg);
reg = /foo["]/g;
expect(parse('[["RegExp","foo[\\"]", "g"]]')).toEqual(reg);
});
Deno.test("parse - Uint8Array", () => {
const value = new Uint8Array([1, 2, 3]);
expect(parse('[["Uint8Array","AQID"]]')).toEqual(
value,
);
});
Deno.test("parse - references", () => {
const inner = { foo: 123 };
const obj = { a: inner, b: [inner, inner] };
const res = parse<typeof obj>('[{"a":1,"b":3},{"foo":2},123,[1,1]]');
expect(res).toEqual(obj);
expect(res.a).toEqual(res.b[0]);
expect(res.a).toEqual(res.b[1]);
});
Deno.test("parse - circular references", () => {
// deno-lint-ignore no-explicit-any
const foo = { foo: null as any };
foo.foo = foo;
expect(parse('[{"foo":0}]')).toEqual(foo);
});
Deno.test("parse - object", () => {
expect(parse('[{"foo":1},42]')).toEqual({ foo: 42 });
});
+186
View File
@@ -0,0 +1,186 @@
import {
INFINITY_NEG,
INFINITY_POS,
NAN,
NULL,
UNDEFINED,
ZERO_NEG,
} from "./constants.ts";
import { HOLE } from "./constants.ts";
// deno-lint-ignore no-explicit-any
export type Stringifiers = Record<string, (value: any) => any>;
/**
* Serializes the following:
*
* - `null`
* - `undefined`
* - `boolean`
* - `number`
* - `bigint`
* - `string`
* - `array`
* - `object` (no prototypes)
* - `Uint8Array`
* - `Date`
* - `RegExp`
* - `Set`
* - `Map`
*
* Circular references are supported and objects with the same reference are
* serialized only once.
*/
export function stringify(data: unknown, custom?: Stringifiers): string {
const out: string[] = [];
const indexes = new Map<unknown, number>();
const res = serializeInner(out, indexes, data, custom);
if (res < 0) {
out.push(String(res));
}
return `[${out.join(",")}]`;
}
function serializeInner(
out: string[],
indexes: Map<unknown, number>,
value: unknown,
custom: Stringifiers | undefined,
): number {
const seenIdx = indexes.get(value);
if (seenIdx !== undefined) return seenIdx;
if (value === undefined) return UNDEFINED;
if (value === null) return NULL;
if (Number.isNaN(value)) return NAN;
if (value === Infinity) return INFINITY_POS;
if (value === -Infinity) return INFINITY_NEG;
if (value === 0 && 1 / value < 0) return ZERO_NEG;
const idx = out.length;
out.push("");
indexes.set(value, idx);
let str = "";
if (typeof value === "number") {
str += String(value);
} else if (typeof value === "boolean") {
str += String(value);
} else if (typeof value === "bigint") {
str += `["BigInt","${value}"]`;
} else if (typeof value === "string") {
str += JSON.stringify(value);
} else if (Array.isArray(value)) {
str += "[";
for (let i = 0; i < value.length; i++) {
if (i in value) {
str += serializeInner(out, indexes, value[i], custom);
} else {
str += HOLE;
}
if (i < value.length - 1) {
str += ",";
}
}
str += "]";
} else if (typeof value === "object") {
if (custom !== undefined) {
for (const k in custom) {
const fn = custom[k];
if (fn === undefined) continue;
const res = fn(value);
if (res === undefined) continue;
serializeInner(out, indexes, res, custom);
str = `["${k}",${idx + 1}]`;
out[idx] = str;
return idx;
}
}
if (value instanceof Date) {
str += `["Date","${value.toISOString()}"]`;
} else if (value instanceof RegExp) {
str += `["RegExp",${JSON.stringify(value.source)}, "${value.flags}"]`;
} else if (value instanceof Uint8Array) {
str += `["Uint8Array","${b64encode(value)}"]`;
} else if (value instanceof Set) {
const items = new Array(value.size);
let i = 0;
value.forEach((v) => {
items[i++] = serializeInner(out, indexes, v, custom);
});
str += `["Set",[${items.join(",")}]]`;
} else if (value instanceof Map) {
const items = new Array(value.size * 2);
let i = 0;
value.forEach((v, k) => {
items[i++] = serializeInner(out, indexes, k, custom);
items[i++] = serializeInner(out, indexes, v, custom);
});
str += `["Map",[${items.join(",")}]]`;
} else {
str += "{";
const keys = Object.keys(value);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
str += JSON.stringify(key) + ":";
// deno-lint-ignore no-explicit-any
str += serializeInner(out, indexes, (value as any)[key], custom);
if (i < keys.length - 1) {
str += ",";
}
}
str += "}";
}
} else if (typeof value === "function") {
throw new Error(`Serializing functions is not supported.`);
}
out[idx] = str;
return idx;
}
// deno-fmt-ignore
const base64abc = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d",
"e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "+", "/",
];
/**
* CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727
* Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation
*/
export function b64encode(buffer: ArrayBuffer): string {
const uint8 = new Uint8Array(buffer);
let result = "",
i;
const l = uint8.length;
for (i = 2; i < l; i += 3) {
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[((uint8[i - 1] & 0x0f) << 2) | (uint8[i] >> 6)];
result += base64abc[uint8[i] & 0x3f];
}
if (i === l + 1) {
// 1 octet yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[(uint8[i - 2] & 0x03) << 4];
result += "==";
}
if (i === l) {
// 2 octets yet to write
result += base64abc[uint8[i - 2] >> 2];
result += base64abc[((uint8[i - 2] & 0x03) << 4) | (uint8[i - 1] >> 4)];
result += base64abc[(uint8[i - 1] & 0x0f) << 2];
result += "=";
}
return result;
}
+109
View File
@@ -0,0 +1,109 @@
import { expect } from "@std/expect";
import { stringify } from "./stringify.ts";
Deno.test("stringify - json", () => {
expect(stringify(2)).toEqual("[2]");
expect(stringify("abc")).toEqual('["abc"]');
expect(stringify(true)).toEqual("[true]");
expect(stringify(false)).toEqual("[false]");
expect(stringify([1, 2, 3])).toEqual("[[1,2,3],1,2,3]");
expect(stringify({ a: 1, b: null, c: [null] })).toEqual(
'[{"a":1,"b":-2,"c":2},1,[-2]]',
);
});
Deno.test("stringify - hole array", () => {
expect(stringify([1, , 3])).toEqual("[[1,-7,2],1,3]");
});
Deno.test("stringify - undefined", () => {
expect(stringify(undefined)).toEqual("[-1]");
});
Deno.test("stringify - Infinity", () => {
expect(stringify(Infinity)).toEqual("[-4]");
expect(stringify(-Infinity)).toEqual("[-5]");
});
Deno.test("stringify - NaN", () => {
expect(stringify(NaN)).toEqual("[-3]");
});
Deno.test("stringify - -0", () => {
expect(stringify(-0)).toEqual("[-6]");
});
Deno.test("stringify - bigint", () => {
const n = BigInt(9007199254740991);
expect(stringify(n)).toEqual(
'[["BigInt","9007199254740991"]]',
);
});
Deno.test("stringify - Date", () => {
const date = new Date("1990-05-31");
expect(stringify(date)).toEqual(
'[["Date","1990-05-31T00:00:00.000Z"]]',
);
});
Deno.test("stringify - RegExp", () => {
let reg = /foo["]/;
expect(stringify(reg)).toEqual(
'[["RegExp","foo[\\"]", ""]]',
);
reg = /foo["]/g;
expect(stringify(reg)).toEqual(
'[["RegExp","foo[\\"]", "g"]]',
);
});
Deno.test("stringify - Set", () => {
expect(stringify(new Set([1, { foo: 1 }]))).toEqual(
'[["Set",[1,2]],1,{"foo":1}]',
);
});
Deno.test("stringify - Map", () => {
expect(stringify(new Map<number, unknown>([[1, { foo: 1 }], [2, 3]])))
.toEqual(
'[["Map",[1,2,3,4]],1,{"foo":1},2,3]',
);
});
Deno.test("stringify - Uint8Array", () => {
const value = new Uint8Array([1, 2, 3]);
expect(stringify(value)).toEqual(
'[["Uint8Array","AQID"]]',
);
});
Deno.test("stringify - references", () => {
const inner = { foo: 123 };
const obj = { a: inner, b: [inner, inner] };
expect(stringify(obj)).toEqual(
'[{"a":1,"b":3},{"foo":2},123,[1,1]]',
);
});
Deno.test("stringify - circular references", () => {
// deno-lint-ignore no-explicit-any
const foo = { foo: null as any };
foo.foo = foo;
expect(stringify(foo)).toEqual(
'[{"foo":0}]',
);
});
Deno.test("stringify - object prototype", () => {
const obj = { __proto__: 123, foo: 1 };
expect(stringify(obj)).toEqual(
'[{"foo":1},1]',
);
});
Deno.test("stringify - throw serializing functions", () => {
const fn = () => {};
expect(() => stringify(fn)).toThrow();
});